Why does struct.pack seemingly return "0"?

Question:

I have a number in integer form which I need to convert into 4 bytes and store it in a list. I am trying to use the struct module but am unable to get it to work:

struct.pack("i", 34);

This returns 0 when I am expecting the binary equivalent to be printed.

Expected output:

[0x00 0x00 0x00 0x22]

But struct.pack is returning empty. What am I doing wrong?

Asked By: user2578666

||

Answers:

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'"x00x00x00'

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'x00x00x00"'

where > indicates big-endian alignment.

Answered By: Martijn Pieters
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.