Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert decimal int to little endian string ('\x##\x##...')

Tags:

python

I want to convert an integer value to a string of hex values, in little endian. For example, 5707435436569584000 would become '\x4a\xe2\x34\x4f\x4a\xe2\x34\x4f'.

All my googlefu is finding for me is hex(..) which gives me '0x4f34e24a4f34e180' which is not what I want.

I could probably manually split up that string and build the one I want but I'm hoping somone can point me to a better option.

like image 302
Matt Avatar asked Dec 05 '22 14:12

Matt


1 Answers

You need to use the struct module:

>>> import struct
>>> struct.pack('<Q', 5707435436569584000)
'\x80\xe14OJ\xe24O'
>>> struct.pack('<Q', 5707435436569584202)
'J\xe24OJ\xe24O'

Here < indicates little-endian, and Q that we want to pack a unsigned long long (8 bytes).

Note that Python will use ASCII characters for any byte that falls within the printable ASCII range to represent the resulting bytestring, hence the 14OJ, 24O and J parts of the above result:

>>> struct.pack('<Q', 5707435436569584202).encode('hex')
'4ae2344f4ae2344f'
>>> '\x4a\xe2\x34\x4f\x4a\xe2\x34\x4f'
'J\xe24OJ\xe24O'
like image 71
Martijn Pieters Avatar answered Dec 14 '22 22:12

Martijn Pieters