I'm messing around with making a binary data parser, and while I could fall back on C, I wanted to see if I could use Python for the task.
I have some inkling of how to get this going, and my current implementation looks something like this:
from ctypes import *
class sHeader(Structure):
_fields_ = [("CC", c_uint8, 4),
("AFC", c_uint8, 2),
("TSC", c_uint8, 2),
("PID", c_uint16, 13),
("TP", c_uint16, 1),
("PSI", c_uint16, 1),
("TEI", c_uint16, 1),
("SyncByte", c_uint8)]
class Header(Union):
_fields_ = [("sData", sTsHeader),
("ulData", c_uint32)]
head = Header()
head.ulData = 0xffffffff
print(head.ulData)
print(head.sData.SyncByte)
print(sHeader.SyncByte)
print(sHeader.TEI)
print(sHeader.PSI)
print(sHeader.TP)
print(sHeader.PID)
print(sHeader.TSC)
print(sHeader.AFC)
print(sHeader.CC)
print(sizeof(sHeader))
print(sizeof(c_uint8))
print(sizeof(c_uint16))
print(sizeof(c_uint32))
Which produces this output:
V:\>C:\Python27\python.exe WidiUnpacker.py
0xffffffffL
0x0
<Field type=c_ubyte, ofs=4, size=1>
<Field type=c_ushort, ofs=2:15, bits=1>
<Field type=c_ushort, ofs=2:14, bits=1>
<Field type=c_ushort, ofs=2:13, bits=1>
<Field type=c_ushort, ofs=2:0, bits=13>
<Field type=c_ubyte, ofs=0:6, bits=2>
<Field type=c_ubyte, ofs=0:4, bits=2>
<Field type=c_ubyte, ofs=0:0, bits=4>
6
1
2
4
So... Looks to me like my bytes aren't bytes so much as words. I don't know enough about Python or ctypes to understand why that is, but it's kind of defeating my purpose at the moment. Any ideas?