]> git.draconx.ca Git - upkg.git/blob - pack.c
Initial commit
[upkg.git] / pack.c
1 #include <stdio.h>
2 #include <limits.h>
3
4 #include "pack.h"
5
6 /* Integer packing. */
7 #define DEFPACK_BE(bits, type) void pack_ ## bits ## _be ( \
8         unsigned char *out, type v \
9 ) { \
10         unsigned i; \
11         for (i = 1; i <= bits/8; i++) { \
12                 out[bits/8 - i] = v % 256; \
13                 v /= 256; \
14         } \
15 }
16
17 #define DEFPACK_LE(bits, type) void pack_ ## bits ## _le ( \
18         unsigned char *out, type v \
19 ) { \
20         unsigned i; \
21         for (i = 0; i < bits/8; i++) { \
22                 out[i] = v % 256; \
23                 v /= 256; \
24         } \
25 }
26
27 DEFPACK_BE(16, unsigned short)
28 DEFPACK_BE(32, unsigned long)
29 #ifdef ULLONG_MAX
30 DEFPACK_BE(64, unsigned long long)
31 #endif
32
33 DEFPACK_LE(16, unsigned short)
34 DEFPACK_LE(32, unsigned long)
35 #ifdef ULLONG_MAX
36 DEFPACK_LE(64, unsigned long long)
37 #endif
38
39 #define DEFUNPACK_BE(bits, type) type unpack_ ## bits ## _be ( \
40         unsigned char *in \
41 ) { \
42         type v = 0; \
43         unsigned i; \
44         for (i = 0; i < bits/8; i++) { \
45                 v *= 256; \
46                 v += in[i]; \
47         } \
48         return v; \
49 }
50
51 #define DEFUNPACK_LE(bits, type) type unpack_ ## bits ## _le ( \
52         unsigned char *in \
53 ) { \
54         type v = 0; \
55         unsigned i; \
56         for (i = 1; i <= bits/8; i++) { \
57                 v *= 256; \
58                 v += in[bits/8 - i]; \
59         } \
60         return v; \
61 }
62
63 DEFUNPACK_BE(16, unsigned short)
64 DEFUNPACK_BE(32, unsigned long)
65 #ifdef ULLONG_MAX
66 DEFUNPACK_BE(64, unsigned long long)
67 #endif
68
69 DEFUNPACK_LE(16, unsigned short)
70 DEFUNPACK_LE(32, unsigned long)
71 #ifdef ULLONG_MAX
72 DEFUNPACK_LE(64, unsigned long long)
73 #endif