2 * Copyright © 2009 Nick Bowler
4 * Portable binary (de-)serialisation of integral types.
6 * License WTFPL2: Do What The Fuck You Want To Public License, version 2.
7 * This is free software: you are free to do what the fuck you want to.
8 * There is NO WARRANTY, to the extent permitted by law.
13 /* Unsigned integer packing. */
14 #define DEFPACK_BE(bits, type) void pack_ ## bits ## _be ( \
15 unsigned char *out, type v \
18 for (i = 1; i <= bits/8; i++) { \
19 out[bits/8 - i] = v % 256; \
24 #define DEFPACK_LE(bits, type) void pack_ ## bits ## _le ( \
25 unsigned char *out, type v \
28 for (i = 0; i < bits/8; i++) { \
34 DEFPACK_BE(16, unsigned short)
35 DEFPACK_BE(32, unsigned long)
37 DEFPACK_BE(64, unsigned long long)
40 DEFPACK_LE(16, unsigned short)
41 DEFPACK_LE(32, unsigned long)
43 DEFPACK_LE(64, unsigned long long)
46 #define DEFUNPACK_BE(bits, type) type unpack_ ## bits ## _be ( \
47 const unsigned char *in \
51 for (i = 0; i < bits/8; i++) { \
58 #define DEFUNPACK_LE(bits, type) type unpack_ ## bits ## _le ( \
59 const unsigned char *in \
63 for (i = 1; i <= bits/8; i++) { \
65 v += in[bits/8 - i]; \
70 DEFUNPACK_BE(16, unsigned short)
71 DEFUNPACK_BE(32, unsigned long)
73 DEFUNPACK_BE(64, unsigned long long)
76 DEFUNPACK_LE(16, unsigned short)
77 DEFUNPACK_LE(32, unsigned long)
79 DEFUNPACK_LE(64, unsigned long long)
83 * Two's complement signed integer packing. This is unlikely to work on
84 * systems that don't themselves use two's complement.
87 #define DEFUNPACK_SBE(bits, max, type) type unpack_s ## bits ## _be ( \
88 const unsigned char *in \
92 int sign = (in[0] & 0x80) ? 1 : 0; \
93 for (i = 0; i < bits/8; i++) { \
95 v += in[i] & (i == 0 ? 0x7f : 0xff); \
97 return sign*(-max-1) + v; \
100 #define DEFUNPACK_SLE(bits, max, type) type unpack_s ## bits ## _le ( \
101 const unsigned char *in \
105 int sign = (in[bits/8 - 1] & 0x80) ? 1 : 0; \
106 for (i = 1; i <= bits/8; i++) { \
108 v += in[bits/8 - i] & (i == 1 ? 0x7f : 0xff); \
110 return sign*(-max-1) + v; \
113 DEFUNPACK_SBE(16, 32767, short)
114 DEFUNPACK_SBE(32, 2147483647l, long)
116 DEFUNPACK_SBE(64, 9223372036854775807ll, long long)
119 DEFUNPACK_SLE(16, 32767, short)
120 DEFUNPACK_SLE(32, 2147483647l, long)
122 DEFUNPACK_SLE(64, 9223372036854775807ll, long long)