Un1
Un1

Reputation: 4132

How to convert a string of numbers back into binary hex (\x values) type?

Edited:

The code below is reading a file (an image in this example) in binary mode:

with open("img_80px.png", mode='rb') as file:
    file_content = file.read()
    binary_data = []
    for i in file_content:
        binary_data.append(i)

Now, printing out file_content will give us a string of hex values in binary b' ' format:

b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00P\x00\x00\x00<
\x08\x06\x00\x00\x00\xf1\'=\x8c\x00\x00\x00\tpHYs\x00\x00\x0fa
\x00\x00\x0fa\x01\xa8?\xa7i\x00\x009\xeeiTXtXML:com.adobe.xmp
\x00\\x00\x00\x00\x00<?xpacket begin="\xef\xbb\xbf" id="W5M0MpCehiHzreSzNTczkc9d"?> 
\n<x:xmpmeta xmlns:x="adobe:ns:meta/" 
x:xmptk="Adobe XMP Core 5.6-c138 79.159824, 2016/09/14-01:09:01 

 ....'

So, the code converts this binary string into the list of numbers by going through file_content and appending each bit into the binary_data (not sure if it's the best way, not sure why it even works), so we're getting this:

[137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13 ....]

The question is, how do I convert this list back into that b'' hex binary string or whatever it is? As you can see, it has \x values and metadata in plain text there. Not sure how to convert it back.

If this way of conversion is disrative, could you suggest another way to convert binary in to a string of integers and back?

I tried doing this:

binary_data_string = "".join(map(str, binary_data))

with open("edited_img_80px.png", mode='wb') as edited_file: 
    binary_hex = bytes.fromhex(binary_data_string)
    edited_file.write(binary_hex)

it throws an error:

ValueError: non-hexadecimal number found in fromhex() arg at position 58313

And I also tried to not convert it to a string to preserve the information about each converted item in the list and be able to convert it back into the binary, but I get:

TypeError: fromhex() argument must be str, not list

Upvotes: 1

Views: 595

Answers (1)

beenjaminnn
beenjaminnn

Reputation: 794

Since you're using Python 3, you can do this:

>>>numbers = [222, 173, 190, 239]
>>>bytes(numbers)
b'\xde\xad\xbe\xef'

Cheers!

Upvotes: 2

Related Questions