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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With