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