compile-snprintf-for-solaris25-20010430
[openafs.git] / src / util / base32.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 #include <afs/param.h>
11 #include "afsutil.h"
12
13 static char *c_xlate = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
14
15
16 /* int_to_base32
17  * Create a base 32 string representation of a number.
18  * The supplied string 's' must be at least 8 bytes long.
19  * Use the b32_string_t tyepdef.
20  */
21 char *int_to_base32(b32_string_t s, int a)
22 {
23     int i, j;
24     unsigned int n;
25
26     i = 0;
27     if (a==0)
28         s[i++] = c_xlate[0];
29     else {
30         j = 25;
31         n = a & 0xc0000000;
32         if (n) {
33             n >>= 30;
34             s[i++] = c_xlate[n];
35             a &= ~0xc0000000;
36         }
37         else {
38             for (; j>=0; j-=5) {
39                 n = a & (0x1f << j);
40                 if (n)
41                     break; /* found highest bits set. */
42             }
43             s[i++] = c_xlate[n>>j];
44             a &= ~(0x1f << j);
45             j -=5;
46         }
47         /* more to do. */
48         for (; j>=0; j-=5) {
49             n = a & (0x1f << j);
50             s[i++] = c_xlate[n>>j];
51             a &= ~(0x1f << j);
52         }
53     }
54     s[i] = '\0';
55     return s;
56 }
57
58 int base32_to_int(char *s)
59 {
60     int n = 0;
61     int result = 0;
62
63     for (; *s; s++) {
64         if (*s <= '9') {
65             n = (int)(*s - '0');
66         }
67         else {
68             n = 10 + (int)(*s - 'A');
69         }
70         result = (result << 5) + n;
71     }
72     return result;
73 }