struct
struct copied to clipboard
pack and unpack binary data.
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 | |
v |
go/pbuf svarint | |
V |
go/pbuf varint |
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
CMake
Compile
mkdir build
cd build
cmake ..
make
make install
headers: build/release/include/struct/.
library: build/release/lib/.
Test
cmake -DSTRUCT_BUILD_TEST=ON ..
make
make test
or run struct_test.
valgrind memory check:
ctest -T memcheck
Bazel
Compile
bazel build //:struct
Test
bazel test //test:struct_test
or
bazel test --test_output=all //test:struct_test
you can use git_repository to fetch struct library.
WORKSPACE:
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
git_repository(
name = "struct",
branch = "master",
remote = "https://github.com/svperbeast/struct",
)
BUILD:
cc_binary(
name = ...,
srcs = [...],
deps = [
"@struct//:struct",
],
)
References
The Practice of Programming (9.1 Formatting Data)
License
Code released under the MIT license.