some tweaks
[mkp224o.git] / base32_to.c
blob781c7e42ca9d646575a619eacfbe9e1ccd29ce2f
1 #include <stddef.h>
2 #include <stdint.h>
3 #include "types.h"
4 #include "base32.h"
6 static const char base32t[32] = {
7 'a', 'b', 'c', 'd', // 0
8 'e', 'f', 'g', 'h', // 1
9 'i', 'j', 'k', 'l', // 2
10 'm', 'n', 'o', 'p', // 3
11 'q', 'r', 's', 't', // 4
12 'u', 'v', 'w', 'x', // 5
13 'y', 'z', '2', '3', // 6
14 '4', '5', '6', '7', // 7
17 +--first octet--+-second octet--+--third octet--+--forth octet--+--fifth octet--+
18 |7 6 5 4 3 2 1 0|7 6 5 4 3 2 1 0|7 6 5 4 3 2 1 0|7 6 5 4 3 2 1 0|7 6 5 4 3 2 1 0|
19 +---------+-----+---+---------+-+-------+-------+-+---------+---+-----+---------+
20 |4 3 2 1 0|4 3 2 1 0|4 3 2 1 0|4 3 2 1 0|4 3 2 1 0|4 3 2 1 0|4 3 2 1 0|4 3 2 1 0|
21 +-1.index-+-2.index-+-3.index-+-4.index-+-5.index-+-6.index-+-7.index-+-8.index-+
23 // masks:
24 // 0xFF 0x7F 0x3F 0x1F 0x0F 0x07 0x03 0x01
25 // 255 127 63 31 15 7 3 1
26 char *base32_to(char *dst,const u8 *src,size_t slen)
28 //printf("slen = %d\n", slen);
29 //printhex(base32t, 32);
30 //printhex(base32f, 256);
31 // base32 eats in 5bit pieces;
32 // closest we can provide is 40, which is 5 bytes
33 size_t i;
34 for (i = 0; i + 4 < slen; i += 5) {
35 //printf("ei!\n");
36 //char *od = dst;
37 *dst++ = base32t[src[i+0] >> 3];
38 *dst++ = base32t[((src[i+0] & 7) << 2) | (src[i+1] >> 6)];
39 *dst++ = base32t[(src[i+1] >> 1) & 31];
40 *dst++ = base32t[((src[i+1] & 1) << 4) | (src[i+2] >> 4)];
41 *dst++ = base32t[((src[i+2] & 15) << 1) | (src[i+3] >> 7)];
42 *dst++ = base32t[((src[i+3]) >> 2) & 31];
43 *dst++ = base32t[((src[i+3] & 3) << 3) | (src[i+4] >> 5)];
44 *dst++ = base32t[src[i+4] & 31];
45 //printhex(od, 8);
47 //char *od = dst;
48 if (i < slen) {
49 //printf("oi!0\n");
50 *dst++ = base32t[src[i+0] >> 3];
51 if (i + 1 < slen) {
52 //printf("oi!1\n");
53 *dst++ = base32t[((src[i+0] & 7) << 2) | (src[i+1] >> 6)];
54 *dst++ = base32t[(src[i+1] >> 1) & 31];
55 if (i + 2 < slen) {
56 //printf("oi!2\n");
57 *dst++ = base32t[((src[i+1] & 1) << 4) | (src[i+2] >> 4)];
58 if (i + 3 < slen) {
59 //printf("oi!3\n");
60 *dst++ = base32t[((src[i+2] & 15) << 1) | (src[i+3] >> 7)];
61 *dst++ = base32t[(src[i+3] >> 2) & 31];
62 *dst++ = base32t[(src[i+3] & 3) << 3];
64 else {
65 *dst++ = base32t[(src[i+2] & 15) << 1];
68 else
69 *dst++ = base32t[(src[i+1] & 1) << 4];
71 else
72 *dst++ = base32t[(src[i+0] & 7) << 2];
74 //printhex(od, dst-od);
75 *dst = 0;
76 return dst;