Why does struct.pack seemingly return “0”?

The output is returned as a byte string, and Python will print such strings as ASCII characters whenever possible:

>>> import struct
>>> struct.pack("i", 34)
b'"\x00\x00\x00'

Note the quote at the start, that’s ASCII codepoint 34:

>>> ord('"')
34
>>> hex(ord('"'))
'0x22'
>>> struct.pack("i", 34)[0]
34

Note that in Python 3, the bytes type is a sequence of integers, each value in the range 0 to 255, so indexing in the last example produces the integer value for the byte displayed as ".

For more information on Python byte strings, see What does a b prefix before a python string mean?

If you expected the ordering to be reversed, then you may need to indicate a byte order:

>>> struct.pack(">i",34)
b'\x00\x00\x00"'

where > indicates big-endian alignment.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)