Skip to content
master
Switch branches/tags
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
src
 
 
 
 
 
 
 
 
 
 

Introduction

struct is a binary data formatting library inspired by 'The Practice of Programming (Brian W. Kernighan, Rob Pike)' and Python struct module.

Format

struct uses following format characters (note that struct does not fully support the Python struct module's format):

Table 1. Byte order

Character Byte order
= native
< little-endian
> big-endian
! network (= big-endian)

Table 2. Format characters

Format C/C++ Type Standard size
b char 1
B unsigned char 1
h short 2
H unsigned short 2
i int 4
I unsigned int 4
l long 4
L unsigned long 4
q long long 8
Q unsigned long long 8
f float 4
d double 8
s char[]
p char[]
x pad bytes

Pack

#include "struct.h"
...
char buf1[BUFSIZ] = {'\0',};
char buf2[BUFSIZ] = {'\0',};
char str[BUFSIZ] = {'\0',};
char fmt[BUFSIZ] = {'\0',};
int val = 42;

struct_pack(buf1, "i", val);

strcpy(str, "test");
snprintf(fmt, sizeof(fmt), "%ds", strlen(str));

struct_pack(buf2, fmt, str);

Unpack

...
int rval;
char rstr[32] = {'\0',};

struct_unpack(buf1, "i", &rval);

struct_unpack(buf2, fmt, rstr);

Install

mkdir build
cd build
cmake ..
make
make install

headers: build/release/include/struct/. library: build/release/lib/.

Test

make test

or run struct_test.

valgrind memory check:

ctest -T memcheck

References

The Practice of Programming (9.1 Formatting Data)

Python struct

License

Code released under the MIT license.