typedef double float64_t;
** packi16() -- store a 16-bit int into a char buffer (like htons())
void packi16(unsigned char *buf, unsigned int i)
*buf++ = i>>8; *buf++ = i;
** packi32() -- store a 32-bit int into a char buffer (like htonl())
void packi32(unsigned char *buf, unsigned long i)
*buf++ = i>>24; *buf++ = i>>16;
*buf++ = i>>8; *buf++ = i;
** unpacki16() -- unpack a 16-bit int from a char buffer (like ntohs())
unsigned int unpacki16(unsigned char *buf)
return (buf[0]<<8) | buf[1];
** unpacki32() -- unpack a 32-bit int from a char buffer (like ntohl())
unsigned long unpacki32(unsigned char *buf)
return (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
** pack() -- store data dictated by the format string in the buffer
** c - 8-bit char f - float, 32-bit
** s - string (16-bit length is automatically prepended)
int32_t pack(unsigned char *buf, char *format, ...)
for(; *format != '\0'; format++) {
h = (int16_t)va_arg(ap, int); // promoted
c = (int8_t)va_arg(ap, int); // promoted
f = (float32_t)va_arg(ap, double); // promoted
l = pack754_32(f); // convert to IEEE 754
** unpack() -- unpack data dictated by the format string into the buffer
void unpack(unsigned char *buf, char *format, ...)
int32_t len, count, maxstrlen=0;
for(; *format != '\0'; format++) {
h = va_arg(ap, int16_t*);
l = va_arg(ap, int32_t*);
f = va_arg(ap, float32_t*);
if (maxstrlen > 0 && len > maxstrlen) count = maxstrlen - 1;
if (isdigit(*format)) { // track max str len
maxstrlen = maxstrlen * 10 + (*format-'0');
if (!isdigit(*format)) maxstrlen = 0;