Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

byte

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

Example...

777007543 = 0x2E 0x50 0x31 0xB7

like image 429
user558383 Avatar asked Dec 16 '22 18:12

user558383


1 Answers

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']
like image 139
martineau Avatar answered Dec 19 '22 08:12

martineau