2 * This file is part of DisOrder.
3 * Copyright (C) 2005, 2007, 2008 Richard Kettlewell
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 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 /** @file lib/basen.c @brief Arbitrary base conversion
20 * The functions in this file handle arbitrary-size non-negative integers,
21 * represented as a bigendian (MSW first) sequence of @c unsigned @c long
22 * words. The words themselves use the native byte order.
29 /** @brief Test whether v is 0
30 * @param v Pointer to bigendian bignum
31 * @param nwords Length of bignum
34 static int zero(const unsigned long *v
, int nwords
) {
37 for(n
= 0; n
< nwords
&& !v
[n
]; ++n
)
42 /** @brief Divide v by m returning the remainder.
43 * @param v Pointer to bigendian bignum
44 * @param nwords Length of bignum
45 * @param m Divisor (must not be 0)
48 * The quotient is stored in @p v.
50 static unsigned divide(unsigned long *v
, int nwords
, unsigned long m
) {
51 unsigned long r
= 0, a
, b
;
54 /* we do the divide 16 bits at a time */
55 for(n
= 0; n
< nwords
; ++n
) {
69 /** @brief Convert v to a chosen base
70 * @param v Pointer to bigendian bignum (modified!)
71 * @param nwords Length of bignum
72 * @param buffer Output buffer
73 * @param bufsize Size of output buffer
74 * @param base Number base (2..62)
75 * @return 0 on success, -1 if the buffer is too small
77 * Converts @p v to a string in the given base using decimal digits, lower case
78 * letter sand upper case letters as digits.
80 int basen(unsigned long *v
,
86 static const char chars
[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
90 return -1; /* overflow */
91 buffer
[--i
] = chars
[divide(v
, nwords
, base
)];
92 } while(!zero(v
, nwords
));
93 memmove(buffer
, buffer
+ i
, bufsize
- i
);
94 buffer
[bufsize
- i
] = 0;