Search code examples
pythonpack

What is the meaning of the letters in the output from struct.pack?


when i change number into hex in struct module of python,

>>> import struct
>>> struct.pack("i",89)
'Y\x00\x00\x00'
>>> struct.pack("i",890)
'z\x03\x00\x00'
>>> struct.pack("i",1890)
'b\x07\x00\x00'

what is the meaning of "Y,z,b" in the output?


Solution

  • You're not converting to hex. You're packing the integer as binary data... in this case, little-endian binary data. The first characters are just the corresponding ASCII characters to the raw bytes; e.g. 89 is Y, 122 is z, and 98 is b.

    • The first pack produces '\x59\x00\x00\x00' for 0x00000059; '\x59' is 'Y'.
    • The second produces '\x7a\x03\x00\x00' for 0x0000037a; '\x7a' is 'z'.
    • The third produces '\x62\x07\x00\x00' for 0x00000762; '\x62' is 'b'.

    See the below ASCII table.


    (source: asciitable.com)