20c3c09638a83a54c6dfad5f1ffebc69a7276292
[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 #ifdef AFS_64BIT_ENV
31 char *int64_to_flipbase64(lb64_string_t s, afs_int64 a)
32 #else
33 char *int64_to_flipbase64(lb64_string_t s, u_int64_t a)
34 #endif
35 {
36     int i, j;
37 #ifdef AFS_64BIT_ENV
38     afs_int64 n;
39 #else
40     u_int64_t n;
41 #endif
42
43     i = 0;
44     if (a==0)
45         s[i++] = c_xlate[0];
46     else {
47         for (n = a & 0x3f; a; n = ((a>>=6) & 0x3f)) {
48             s[i++] = c_xlate[n];
49         }
50     }
51     s[i] = '\0';
52     return s;
53 }
54
55
56 /* Mapping: +=0, ==1, 0-9 = 2-11, A-Z = 12-37, a-z = 38-63 */
57 #ifdef AFS_64BIT_ENV
58 afs_int64 flipbase64_to_int64(char *s)
59 #else
60 int64_t flipbase64_to_int64(char *s)
61 #endif
62 {
63 #ifdef AFS_64BIT_ENV
64     afs_int64 n = 0;
65     afs_int64 result = 0;
66 #else
67     int64_t n = 0;
68     int64_t result = 0;
69 #endif
70     int shift;
71
72     for (shift = 0; *s; s++, shift += 6) {
73         if (*s == '+') n = 0;
74         else if (*s == '=') n = 1;
75         else if (*s <= '9') {
76             n = 2 + (int)(*s - '0');
77         }
78         else if (*s <= 'Z') {
79             n = 12 + (int)(*s - 'A');
80         }
81         else if (*s <= 'z') {
82             n = 38 + (int)(*s - 'a');
83         }
84         n <<= shift;
85         result |= n ;
86     }
87     return result;
88 }
89
90
91 #endif /* AFS_NAMEI_ENV */