aboutsummaryrefslogtreecommitdiff
path: root/src/lib9/u16.c
blob: d9f41e462c2dc65a0e8fd3eca556fb2a82255874 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <lib9.h>
static char t16e[] = "0123456789ABCDEF";

int
dec16(uchar *out, int lim, char *in, int n)
{
	int c, w = 0, i = 0;
	uchar *start = out;
	uchar *eout = out + lim;

	while(n-- > 0){
		c = *in++;
		if('0' <= c && c <= '9')
			c = c - '0';
		else if('a' <= c && c <= 'z')
			c = c - 'a' + 10;
		else if('A' <= c && c <= 'Z')
			c = c - 'A' + 10;
		else
			continue;
		w = (w<<4) + c;
		i++;
		if(i == 2){
			if(out + 1 > eout)
				goto exhausted;
			*out++ = w;
			w = 0;
			i = 0;
		}
	}
exhausted:
	return out - start;
}

int
enc16(char *out, int lim, uchar *in, int n)
{
	uint c;
	char *eout = out + lim;
	char *start = out;

	while(n-- > 0){
		c = *in++;
		if(out + 2 >= eout)
			goto exhausted;
		*out++ = t16e[c>>4];
		*out++ = t16e[c&0xf];
	}
exhausted:
	*out = 0;
	return out - start;
}