chiark / gitweb /
Import from Arch revision:
[disorder] / lib / basen.c
CommitLineData
460b9539 1/*
2 * This file is part of DisOrder.
3 * Copyright (C) 2005 Richard Kettlewell
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18 * USA
19 */
20
21#include <config.h>
22#include "types.h"
23
24#include <string.h>
25
26#include "basen.h"
27
28/* test whether v is 0 */
29static int zero(const unsigned long *v, int nwords) {
30 int n;
31
32 for(n = 0; n < nwords && !v[n]; ++n)
33 ;
34 return n == nwords;
35}
36
37/* divide v by m returning the remainder */
38static unsigned divide(unsigned long *v, int nwords, unsigned long m) {
39 unsigned long r = 0, a, b;
40 int n;
41
42 /* we do the divide 16 bits at a time */
43 for(n = 0; n < nwords; ++n) {
44 a = v[n] >> 16;
45 b = v[n] & 0xFFFF;
46 a += r << 16;
47 r = a % m;
48 a /= m;
49 b += r << 16;
50 r = b % m;
51 b /= m;
52 v[n] = (a << 16) + b;
53 }
54 return r;
55}
56
57int basen(unsigned long *v,
58 int nwords,
59 char buffer[],
60 size_t bufsize,
61 unsigned base) {
62 size_t i = bufsize;
63 static const char chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
64
65 do {
66 if(i <= 1) return -1; /* overflow */
67 buffer[--i] = chars[divide(v, nwords, base)];
68 } while(!zero(v, nwords));
69 memmove(buffer, buffer + i, bufsize - i);
70 buffer[bufsize - i] = 0;
71 return 0;
72}
73
74/*
75Local Variables:
76c-basic-offset:2
77comment-column:40
78fill-column:79
79End:
80*/
81/* arch-tag:iGDXjhkM2cdyv0RSlftgGQ */