pack.c 1.34 KB
Newer Older
1
2
#include <stdio.h>

3
typedef unsigned int number;
4

5
unsigned char do_pack(unsigned char *buf, number i) 
6
7
8
{
	printf("do_pack %lu == %lx\n", i, i);

9
	number tmp = i;
10
11
12
13
14
15
16
17
18
19
20
	unsigned char res = 0;

	while ( tmp >= 0x80 ) {
		buf[res] = (tmp & 0x7f) | 0x80;
	        tmp >>= 7;
		res++;
	}
	buf[res] = tmp;
	return res+1;
}

21
number do_unpack(unsigned char *buf) 
22
{
23
	number res=0;
24
25
26
	unsigned char i=0;
	unsigned char cont=1;
	do {
27
28
29
30
		unsigned char c = buf[i];
		res |= (c & 0x7f) << 7*i; 
		cont = c & 0x80;
		i++;
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
	} while(cont);

	return res;
}

void print_packed(unsigned char *buf, unsigned char len)
{
	int i;
	
	for(i=0; i<len;i++) {
		printf("%2x   ", buf[i]);
	}
	printf("\n");
}

int main()
{
	unsigned char buf[10];
	unsigned char len;

	len = do_pack(buf, 10);
	print_packed(buf, len);
	printf("... unpacks to %u\n\n", do_unpack(buf));

	len = do_pack(buf, 100);
	print_packed(buf, len);
	printf("... unpacks to %u\n\n", do_unpack(buf));

	len = do_pack(buf, 1000);
	print_packed(buf, len);
	printf("... unpacks to %u\n\n", do_unpack(buf));

	len = do_pack(buf, 100000);
	print_packed(buf, len);
	printf("... unpacks to %u\n\n", do_unpack(buf));

	len = do_pack(buf, 2345678901);
	print_packed(buf, len);
	printf("... unpacks to %u\n\n", do_unpack(buf));

71
	len = do_pack(buf, 0xffffffff);
72
73
74
75
76
	print_packed(buf, len);
	printf("... unpacks to %lx\n", do_unpack(buf));

	return 0;
}