bitstruct
bitstruct copied to clipboard
Packing data across byte boundaries
Hi, thanks for an awesome tool. I have been using it really happily with a lot of data that is mostly multiples of 8 bits or sets of bools and enums. However I have hit a new challenge with a specific message type to encode. It packs like the below and I have struggled to work out if there is a corresponding format string.
a = message_id: 6 bit uint
b = repeat_count: 2 bit uint
c = sender: 30 bit uint
d = status: 4 bit uint
e ... etc
it continues on with other values, including a 27 and a 28 bit signed integer. The packed fields should come out like this:
b1 b0 a6 a a a a a0 | c7 c c c c c c c0 | c14 c c c c c c c8 | c23 c c c c c c c9 | d1 d0 c29 c c c c c24 | e5 e e e e e0 d3 d2 | ...
Figured it was a worth a shot asking what to try next
i guess i have a similar issue
unpacking using struct.unpack works as intended, or reading raw bytes and convert them manually
>>> import bitstruct
>>> import struct
>>> data = b"\x02\x3A" # lsb 16bit integer 0x3A02 = 14850
>>> ok = struct.unpack("<H", data)
>>> print("struct.unpack", ok[0])
struct.unpack 14850
>>> nok = bitstruct.unpack("<u16", data)
>>> print("bitstruct.unpack", nok[0])
bitstruct.unpack 23616
>>> raw = bitstruct.unpack("r16", data)
>>> fix = int.from_bytes(raw[0], "little")
>>> print("bitstruct.unpack workaround", fix)
bitstruct.unpack workaround 14850