Python 2: Why is this bytestring order switched in struct.pack() and struct.unpack() methods?
Question: 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?

e.g. 0xbba1 -> '\xbb\xa1' '\xbb\xa1' -> 0xbba1


Answer: It's a [little-endian/big-endian](http://en.wikipedia.org/wiki/Endianness)
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'
    

