Dd Pp
Dd Pp

Reputation: 5957

little endian in python

Mysystem endian is little,

>>> struct.pack('i',70691357)
'\x1d\xaa6\x04'
>>> int("0x436aa1d",16)
70691357

to overturn 0x436aa1d is 1d a a6 43 is not 1d a a6 04 ,what is the reason?

Upvotes: 0

Views: 1740

Answers (3)

martineau
martineau

Reputation: 123393

You could use a one-liner like this to display the bytes of a string in hexadecimal regardless of their value:

def hexify(s):
    return ''.join(map(lambda c: '\\x{:02x}'.format(ord(c)), s))

print hexify(struct.pack('i', 70691357))  # \x1d\xaa\x36\x04

Upvotes: 0

monkut
monkut

Reputation: 43832

If you want a pretty print output you can use binascii.hexlify()

>>> import binascii
>>> binascii.hexlify(struct.pack('i',70691357))
'1daa3604'

Upvotes: 2

Mark Ransom
Mark Ransom

Reputation: 308101

The string that was printed out should be interpreted as 0x1d 0xaa ord('6') 0x04, where ord('6') = 0x36. Reversing the bytes and putting it together makes 0x0436aa1d.

Upvotes: 2

Related Questions