Skip to content

Instantly share code, notes, and snippets.

@McPolemic
Created June 21, 2012 05:05
Show Gist options
  • Save McPolemic/2963976 to your computer and use it in GitHub Desktop.
Save McPolemic/2963976 to your computer and use it in GitHub Desktop.
Convert C-style flat-file structs to python dicts
import struct
def parse(my_struct, my_string):
"""Takes a large string such as the following:
char record1[2];
char record2[10];
char record3[15];
char record4[12];
and a target string that represents the struct's data, and returns a
dict with the struct entries as keys and the unpacked data as values."""
fmt_string = ''
keys_in_order = []
values_in_order = []
total_length = 0
for line in my_struct.split('\n'):
#Skip blank lines
if line.strip() == '':
continue
#Skip comment lines
if '/*' in line or '//' in line:
continue
#Check for data type. Only 'char' supported for now
if line.strip().split()[0] == 'char':
if '[' in line and ']' in line:
#determine length of string
length = int(line.split('[')[1].split(']')[0])
fmt = '%ds' % length
else:
length = 1
fmt = 'c'
else:
raise KeyError
#Now determine key name
key = line.split('[')[0].strip().split(' ')[-1]
#Append format and keys
fmt_string += fmt
total_length += length
keys_in_order.append(key)
if total_length != len(my_string):
raise ValueError("Struct declares a string %d long, input string is %d" % (len(my_string),total_length))
values_in_order = struct.unpack(fmt_string, my_string)
return_dict = dict(zip(keys_in_order, values_in_order))
return return_dict
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment