Skip to content

Instantly share code, notes, and snippets.

@alexjaw
Created March 17, 2022 08:13
Show Gist options
  • Save alexjaw/93709a77f3ec2461757f278f786510ca to your computer and use it in GitHub Desktop.
Save alexjaw/93709a77f3ec2461757f278f786510ca to your computer and use it in GitHub Desktop.
Code example for how to decode c structs
# See also
# https://docs.python.org/3/library/struct.html#format-strings
# https://stackoverflow.com/questions/17244488/reading-struct-in-python-from-created-struct-in-c
'''
// Create c struct
#include <stdio.h>
typedef struct { char c; double v; int t;} save_type;
int main() {
// 1 + 8 + 4 = 13 bytes
// 1+7 + 8 + 4+4 = 24 bytes since we are on a 64-bit machine
save_type s = { 's', 12.1f, 17};
FILE *f = fopen("output", "w");
fwrite(&s, sizeof(save_type), 1, f);
fclose(f);
return 0;
'''
import struct
fmt_str = 'c7x d i4x'
s = struct.Struct(fmt_str)
print(f'Format string: {s.format}. It uses: {s.size} bytes')
with open('output', 'rb') as f:
chunk = f.read(s.size)
while len(chunk) > 0 :
unpacked = s.unpack(chunk)
print(f'Unpacked Values: {unpacked}')
chunk = f.read(s.size)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment