figbar
figbar

Reputation: 794

Python converting bytes to hex and back

I have a long hex string that looks like so: "fffffffffffffffff...". It is part of a processed bitmap image (ppm format). I convert the string to a usable list of numbers, like: [255, 255, 255, 255, 255, 255, 255...](and I later extract RGB values from it), however I am unable to convert the numbers back to this hex string properly.

raw_hex = "fffffffffffffffffff..." # a long string taken from a file
list_of_ints = [int(raw_hex[i:i+2], 16) for i in range(0, len(raw_hex), 2)] # a list of ints, looks like [255,255,255...] 

I then attempt to reverse the process by doing the following command (I want to obtain raw_hex again from list_of_ints:

reversed_hex = ''.join([format(int(i), 'x') for i in data])

This appears to provide a similar output ("ffffffffffffffffff..."). However I can tell that they are not the same, as running len(raw_hex) and len(reversed_hex), produces 1500000 and 1490871. However I know the intermediate command is working properly, as len(list_of_ints) yields 750000, which is what I expect. So what am I doing wrong, and how can I obtain the original hex string from the integer list?

Upvotes: 1

Views: 1095

Answers (2)

Mark Tolonen
Mark Tolonen

Reputation: 178429

There are convenience functions to convert from a hexadecimal string to bytes and back:

>>> raw_hex = 'ffffffff'
>>> bytes.fromhex(raw_hex)
b'\xff\xff\xff\xff'
>>> ints = list(bytes.fromhex(raw_hex))
>>> ints
[255, 255, 255, 255]
>>> bytes(ints)
b'\xff\xff\xff\xff'
>>> bytes(ints).hex()
'ffffffff'

Upvotes: 1

General Poxter
General Poxter

Reputation: 554

I assume the image raw hex includes padded 0s? If that's the case, these padded 0s are being lost when converting from the ints back to hex. This can be fixed as follows:

reversed_hex = ''.join([format(int(i), '02x') for i in data])

Upvotes: 2

Related Questions