+#include <stdio.h>
+#include <limits.h>
+
+#include "pack.h"
+
+/* Integer packing. */
+#define DEFPACK_BE(bits, type) void pack_ ## bits ## _be ( \
+ unsigned char *out, type v \
+) { \
+ unsigned i; \
+ for (i = 1; i <= bits/8; i++) { \
+ out[bits/8 - i] = v % 256; \
+ v /= 256; \
+ } \
+}
+
+#define DEFPACK_LE(bits, type) void pack_ ## bits ## _le ( \
+ unsigned char *out, type v \
+) { \
+ unsigned i; \
+ for (i = 0; i < bits/8; i++) { \
+ out[i] = v % 256; \
+ v /= 256; \
+ } \
+}
+
+DEFPACK_BE(16, unsigned short)
+DEFPACK_BE(32, unsigned long)
+#ifdef ULLONG_MAX
+DEFPACK_BE(64, unsigned long long)
+#endif
+
+DEFPACK_LE(16, unsigned short)
+DEFPACK_LE(32, unsigned long)
+#ifdef ULLONG_MAX
+DEFPACK_LE(64, unsigned long long)
+#endif
+
+#define DEFUNPACK_BE(bits, type) type unpack_ ## bits ## _be ( \
+ unsigned char *in \
+) { \
+ type v = 0; \
+ unsigned i; \
+ for (i = 0; i < bits/8; i++) { \
+ v *= 256; \
+ v += in[i]; \
+ } \
+ return v; \
+}
+
+#define DEFUNPACK_LE(bits, type) type unpack_ ## bits ## _le ( \
+ unsigned char *in \
+) { \
+ type v = 0; \
+ unsigned i; \
+ for (i = 1; i <= bits/8; i++) { \
+ v *= 256; \
+ v += in[bits/8 - i]; \
+ } \
+ return v; \
+}
+
+DEFUNPACK_BE(16, unsigned short)
+DEFUNPACK_BE(32, unsigned long)
+#ifdef ULLONG_MAX
+DEFUNPACK_BE(64, unsigned long long)
+#endif
+
+DEFUNPACK_LE(16, unsigned short)
+DEFUNPACK_LE(32, unsigned long)
+#ifdef ULLONG_MAX
+DEFUNPACK_LE(64, unsigned long long)
+#endif