Why can't I unzip a float with other types and get the expected result?

I'm trying to parse some data packed into this binary, and the Python structural module is causing me all kinds of problems. It seems like it will not give me the correct float variable when it tries to do more than one type at a time:

import struct # a fragment of the binary file a = '\x39\x00\xFF\x00\x00\x0A\x00\x1F\x05\xDC\x42\x31\x30\x00\xFF\x00\x00\x0A\x00\xB5\x01\xE6\x42' struct.unpack_from('1sxHxbxf', a) # returns ('9', 255, 10, 2.8355782166755716e-09), but struct.unpack_from('f',a[7:]) # gives the expected (110.01000213623047,) 
+4
source share
1 answer

By default, C types are represented in the native machine format and byte order and are correctly aligned by skipping the missing bytes, if necessary (in accordance with the rules used by the C compiler).

In the unpacking, it is assumed that the float will be aligned on an 8-byte boundary and will skip more than 1 byte of filling to get there. You can confirm this by skipping 1 byte yourself:

 >>> struct.unpack_from('1sxHxbxf', a) ('9', 255, 10, 2.8355782166755716e-09) >>> struct.unpack_from('f',a[8:]) (2.8355782166755716e-09,) 

To disable alignment, add = , < , > or ! to the beginning of the format string ,

 >>> struct.unpack_from('=1sxHxbxf', a) ('9', 255, 10, 110.01000213623047) 
+8
source

All Articles