u16.c (808B)
1 #include <lib9.h> 2 static char t16e[] = "0123456789ABCDEF"; 3 4 int 5 dec16(uchar *out, int lim, char *in, int n) 6 { 7 int c, w = 0, i = 0; 8 uchar *start = out; 9 uchar *eout = out + lim; 10 11 while(n-- > 0){ 12 c = *in++; 13 if('0' <= c && c <= '9') 14 c = c - '0'; 15 else if('a' <= c && c <= 'z') 16 c = c - 'a' + 10; 17 else if('A' <= c && c <= 'Z') 18 c = c - 'A' + 10; 19 else 20 continue; 21 w = (w<<4) + c; 22 i++; 23 if(i == 2){ 24 if(out + 1 > eout) 25 goto exhausted; 26 *out++ = w; 27 w = 0; 28 i = 0; 29 } 30 } 31 exhausted: 32 return out - start; 33 } 34 35 int 36 enc16(char *out, int lim, uchar *in, int n) 37 { 38 uint c; 39 char *eout = out + lim; 40 char *start = out; 41 42 while(n-- > 0){ 43 c = *in++; 44 if(out + 2 >= eout) 45 goto exhausted; 46 *out++ = t16e[c>>4]; 47 *out++ = t16e[c&0xf]; 48 } 49 exhausted: 50 *out = 0; 51 return out - start; 52 }