Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using struct pack in python

Tags:

python

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?

like image 416
user2578666 Avatar asked Sep 10 '13 12:09

user2578666


1 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'"\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.

like image 139
Martijn Pieters Avatar answered Oct 04 '22 05:10

Martijn Pieters