revert-ubik-changes-20080405
[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 <afsconfig.h>
11 #include <afs/param.h>
12
13 RCSID
14     ("$Header$");
15
16 #include "afsutil.h"
17
18 static char *c_xlate = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
19
20
21 /* int_to_base32
22  * Create a base 32 string representation of a number.
23  * The supplied string 's' must be at least 8 bytes long.
24  * Use the b32_string_t tyepdef.
25  */
26 char *
27 int_to_base32(b32_string_t s, int a)
28 {
29     int i, j;
30     unsigned int n;
31
32     i = 0;
33     if (a == 0)
34         s[i++] = c_xlate[0];
35     else {
36         j = 25;
37         n = a & 0xc0000000;
38         if (n) {
39             n >>= 30;
40             s[i++] = c_xlate[n];
41             a &= ~0xc0000000;
42         } else {
43             for (; j >= 0; j -= 5) {
44                 n = a & (0x1f << j);
45                 if (n)
46                     break;      /* found highest bits set. */
47             }
48             s[i++] = c_xlate[n >> j];
49             a &= ~(0x1f << j);
50             j -= 5;
51         }
52         /* more to do. */
53         for (; j >= 0; j -= 5) {
54             n = a & (0x1f << j);
55             s[i++] = c_xlate[n >> j];
56             a &= ~(0x1f << j);
57         }
58     }
59     s[i] = '\0';
60     return s;
61 }
62
63 int
64 base32_to_int(char *s)
65 {
66     int n = 0;
67     int result = 0;
68
69     for (; *s; s++) {
70         if (*s <= '9') {
71             n = (int)(*s - '0');
72         } else {
73             n = 10 + (int)(*s - 'A');
74         }
75         result = (result << 5) + n;
76     }
77     return result;
78 }