ba6ef914a2c5678475ccff5737c18c124da6007b
[openafs.git] / src / util / flipbase64.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
12 #if defined(AFS_NAMEI_ENV)
13 #include <sys/types.h>
14 #include "afsutil.h"
15
16 /* This version of base64 gets it right and starts converting from the low
17  * bits to the high bits. 
18  */
19 /* This table needs to be in lexical order to efficiently map back from
20  * characters to the numerical value.
21  */
22 static char c_xlate[80] =
23         "+=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
24
25 /* int_to_base64
26  * Create a base 64 string representation of a number.
27  * The supplied string 's' must be at least 12 bytes long.
28  * lb64_string in stds.h provides a typedef to get the length.
29  */
30 char *int64_to_flipbase64(lb64_string_t s, uint64_t a)
31 {
32     int i, j;
33     int64_t n;
34
35     i = 0;
36     if (a==0)
37         s[i++] = c_xlate[0];
38     else {
39         for (n = a & 0x3f; a; n = ((a>>=6) & 0x3f)) {
40             s[i++] = c_xlate[n];
41         }
42     }
43     s[i] = '\0';
44     return s;
45 }
46
47
48 /* Mapping: +=0, ==1, 0-9 = 2-11, A-Z = 12-37, a-z = 38-63 */
49 int64_t flipbase64_to_int64(char *s)
50 {
51     int64_t n = 0;
52     int64_t result = 0;
53     int shift;
54
55     for (shift = 0; *s; s++, shift += 6) {
56         if (*s == '+') n = 0;
57         else if (*s == '=') n = 1;
58         else if (*s <= '9') {
59             n = 2 + (int)(*s - '0');
60         }
61         else if (*s <= 'Z') {
62             n = 12 + (int)(*s - 'A');
63         }
64         else if (*s <= 'z') {
65             n = 38 + (int)(*s - 'a');
66         }
67         n <<= shift;
68         result |= n ;
69     }
70     return result;
71 }
72
73
74 #endif /* AFS_NAMEI_ENV */