How to convert decimal number to byte list in python

How do you turn a long unsigned int into a four byte list in hexidecimal?

Example...

777007543 = 0x2E 0x50 0x31 0xB7

+2
source share
5 answers

The easiest way is to use a struct module from a list comprehension:

 import struct print [hex(ord(b)) for b in struct.pack('>L',777007543)] # ['0x2e', '0x50', '0x31', '0xb7'] 

It's a little harder to get uppercase hexadecimal digits, but not so bad:

 import string import struct xlate = string.maketrans('abcdef', 'ABCDEF') print [hex(ord(b)).translate(xlate) for b in struct.pack('>L',777007543)] # ['0x2E', '0x50', '0x31', '0xB7'] 
+3
source

Use this:

 In [1]: hex(777007543) Out[1]: '0x2e5031b7' 

You should be able to reformat it here.

+3
source

Using struct module :

 In [6]: import struct In [14]: map(hex,struct.unpack('>4B',struct.pack('>L',777007543))) Out[14]: ['0x2e', '0x50', '0x31', '0xb7'] 

or, if capitalization is important,

 In [17]: map('0x{0:X}'.format,struct.unpack('>4B',struct.pack('>L',777007543))) Out[17]: ['0x2E', '0x50', '0x31', '0xB7'] 
+3
source

The Struct module will give you the actual bytes:

 >>> struct.pack('L',777007543) '.P1\xb7' 
0
source

Lines + structure is really too complex for this simple task

 >>> x=777007543 >>> [hex(0xff&x>>8*i) for i in 3,2,1,0] ['0x2e', '0x50', '0x31', '0xb7'] >>> [hex(0xff&x>>8*i).upper() for i in 3,2,1,0] ['0X2E', '0X50', '0X31', '0XB7'] 

Here is a quick comparison using ipython

 In [1]: import struct In [2]: x=777007543 In [3]: timeit [hex(ord(b)) for b in struct.pack('>L',x)] 100000 loops, best of 3: 2.06 us per loop In [4]: timeit [hex(0xff&x>>8*i) for i in 3,2,1,0] 1000000 loops, best of 3: 1.35 us per loop In [5]: timeit [hex(0xff&x>>i) for i in 24,16,8,0] 1000000 loops, best of 3: 1.15 us per loop 
0
source

Source: https://habr.com/ru/post/1334223/


All Articles