Python: unexpected behavior from struct pack ()

I had a problem using an struct.pack()integer for packaging.

WITH

struct.pack("BIB", 1, 0x1234, 0) 

I expect

'\x01\x00\x00\x034\x12\x00'

but instead i got

'\x01\x00\x00\x004\x12\x00\x00\x00'

I probably missed something. Please, help.

+4
source share
2 answers
'\x01\x00\x00\x004\x12\x00\x00\x00'
                 ^ this '4' is not part of a hex escape

actually the same as:

'\x01\x00\x00\x00\x34\x12\x00\x00\x00'

Since the ASCII code for "4" is 0x34.

Since you used the standard (native) format, Python used its own alignment for the data, so the second field was aligned with an offset of 4 and 3 zeros that were added before it.

, , >BIB <BIB ( big-endian little-endian ). '\x01\x00\x00\x12\x34\x00' '\x01\x34\x12\x00\x00\x00'. , , , , big-endian little-endian 0x1234.

. : , .

+8

docs

C- , C ; , . , C . , , , : . ", ".

, . (chr(0x34) == '4')

>>> struct.pack(">BIB", 1, 0x1234, 0)
'\x01\x00\x00\x124\x00'
+2

All Articles