31

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 in python 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?

Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
user2578666
  • 1,113
  • 3
  • 12
  • 18

1 Answers1

56

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.

Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187