Build parsing for unaligned int field?

I use this cute little construct package to parse binary data. However, I came across a situation where the format is defined as:

31 24 23 0 +-------------------------+ | status | an int number | +-------------------------+ 

Basically, the higher 8 bits are used for status, and 3 bytes for an integer: int type with higher bits disguised. I lost a bit, which is the correct way to determine the format:

  • The brute force method is to define it as ULInt32 and do the masking itself.
  • Anyway, can I use BitStruct to fix the problem?

Edit

Assuming Little Endian and based on the example of jterrace and swapped = True sentence, I think this will work in my case:

 sample = "\xff\x01\x01\x01" c = BitStruct("foo", BitField("i", 24, swapped=True), BitField("status", 8)) c.parse(sample) Container({'i': 66047, 'status': 1}) 

thanks

Oliver

+4
source share
2 answers

It would be easy if the design contained Int24 types, but it is not. Instead, you can specify the bit length yourself as follows:

 >>> from construct import BitStruct, BitField >>> sample = "\xff\x01\x01\x01" >>> c = BitStruct("foo", BitField("status", 8), BitField("i", 24)) >>> c.parse(sample) Container({'status': 255, 'i': 65793}) 

Note. The value \x01\x01\x01 is 65536 + 256 + 1 = 65793

+2
source
 BitStruct("foo", BitField("status", 8), BitField("number", 24)) 
0
source

Source: https://habr.com/ru/post/1394486/


All Articles