user558383
user558383

Reputation: 77

How do you convert a decimal number into a list of bytes in python

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

Example...

777007543 = 0x2E 0x50 0x31 0xB7

Upvotes: 4

Views: 9661

Answers (5)

martineau
martineau

Reputation: 123531

The simplest way I can think of is to use the struct module from within a list comprehension:

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

It's a little bit more complicated to get uppercase hex digits, but not that 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']

Update

Since from your comments it sounds like you may be using Python 3 — even though your question doesn't have a "python-3.x" tag — and that fact that nowadays most folks are using the later version, here's code illustrating how to do it that will work in both versions (producing uppercase hexadecimal letters):

import struct
import sys

if sys.version_info < (3,):  # Python 2?
    def hexfmt(val):
        return '0x{:02X}'.format(ord(val))
else:
    def hexfmt(val):
        return '0x{:02X}'.format(val)

byte_list = [hexfmt(b) for b in struct.pack('>L', 777007543)]
print(byte_list)  # -> ['0x2E', '0x50', '0x31', '0xB7']

Upvotes: 4

John La Rooy
John La Rooy

Reputation: 304473

Strings + struct are really overkill for this simple problem

>>> 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

Upvotes: 1

unutbu
unutbu

Reputation: 880927

Using the 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']

Upvotes: 3

Tyler Eaves
Tyler Eaves

Reputation: 13133

Struct module will give you the actual bytes:

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

Upvotes: 1

gruszczy
gruszczy

Reputation: 42228

Use this:

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

you should be able to reformat it from here.

Upvotes: 4

Related Questions