How do you turn a long unsigned int into a list of four bytes in hexidecimal?
Example...
777007543 = 0x2E 0x50 0x31 0xB7
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With