Don
Don

Reputation: 25

How to append a list of Hex to one Hex number

I have a list of hex bytes strings like this

['0xe1', '0xd7', '0x7', '0x0']

(as read from a binary file)

I want to flip the list and append the list together to create one hex number,

['0x07D7E1']

How do I format the list to this format?

Upvotes: 2

Views: 4241

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121366

Concatenate your hex numbers into one string:

'0x' + ''.join([format(int(c, 16), '02X') for c in reversed(inputlist)])

This does include the 00 byte explicitly in the output:

>>> inputlist = ['0xe1', '0xd7', '0x7', '0x0']
>>> '0x' + ''.join([format(int(c, 16), '02X') for c in reversed(inputlist)])
'0x0007D7E1'

However, I'd look into reading your binary file format better; using struct for example to unpack bytes directly from the file into proper integers in the right byte order:

>>> import struct
>>> bytes = ''.join([chr(int(c, 16)) for c in inputlist])
>>> value = struct.unpack('<I', bytes)[0]
>>> print hex(value)
0x7d7e1

Upvotes: 4

Related Questions