What is the meaning of the letters in the output f

2020-08-03 13:30发布

问题:

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?

回答1:

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)



回答2:

Note that you are not converting to hex, you are converting data to raw bytes. The console is then echoing those bytes back to you, in a form that can be entered again as python literal strings.

So python is printing the literal byte string, and some of the bytes can be represented as ASCII characters; most bytes in the range 0x21-0x7E can be printed as such:

>>> '\x22'
'"'
>>> '\x50'
'P'

Thus, 'Y', 'z', and 'b' are bytes that fall in that range and python just prints them as ASCII instead of \x escapes:

>>> '\x59'
'Y'
>>> '\x62'
'b'
>>> '\x7a'
'z'

The rest of your bytes fall outside of the printable ASCII range, so python is representing these as \xFF literals, which happens to use hex notation.



回答3:

lets go line by line
but first we have to understand little-endian format and char value:
32 bit little-endian int have the most significant bits on the right
so the value of the in memory hex (0x01, 0x02, 0x03, 0x04) is really (0x04, 0x03, 0x02, 0x01)
char value 'Y' = 0x59 = 89, 'z' = 0x7a = 122, 'b' = 0x62 = 98

'Y\x00\x00\x00' = 0x59, 0x00, 0x00, 0x00 /Data in memory
'Y\x00\x00\x00' = 0x00000059 = 89 /Real integer value

'z\x03\x00\x00' = 0x7a, 0x03, 0x00, 0x00 /Data in memory
'z\x03\x00\x00' = 0x0000037a = 890 /Real integer value

'b\x0b\x07\x00' = 0x62, 0x07, 0x00, 0x00 /Data in memory
'b\x0b\x07\x00' = 0x00000762 = 1890 /Real integer value



标签: python pack