简体   繁体   中英

Python 2: Why is this bytestring order switched in struct.pack() and struct.unpack() methods?

In Python 2.7.5, I have an hex 0xbba1, and I want to change it in bytestring format.

>>> bytetoint = lambda bytestr: struct.unpack('H', bytestr)[0]
>>> hextobyte = lambda hexnum: struct.pack('H', hexnum)
>>> hextobyte(0xbba1)
'\xa1\xbb'
>>> hex(bytetoint('\xa1\xbb'))
'0xbba1'

Why are the first byte '\\xa1' and the second byte'\\xbb' switched in place?

How can I get the right bytestring from hex, or vice versa?

eg 0xbba1 -> '\\xbb\\xa1' '\\xbb\\xa1' -> 0xbba1

It's a little-endian/big-endian thing. You can't really say the bytes are switched, because nothing in the int definition says what order the bytes representing it are laid out in.

The result you have is a perfectly usable little-endian representation. If you want to force big-endian, which may look better to a human reader, you can specify the byte order with > :

>>> import struct
>>> struct.pack('>H', 0xbba1)
'\xbb\xa1'
>>> hex(struct.unpack('>H', '\xbb\xa1')[0])
'0xbba1'

First read about endianness so that you understand where this problem is coming from. On a typical x86-based computer with a little-endian CPU, the correct in-memory representation of int(0xbba1) is the two bytes a1 bb , in that order.

If you really want to decode a byte string from the opposite big-endian order, see this section of the struct docs :

bytestring = `\xbb\xa1`
hex( struct.unpack('>H','\xbb\xa1')[0] )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM