简体   繁体   English

如何将数字字符串转换回二进制十六进制(\\ x值)类型?

[英]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: 现在,打印出file_content将以二进制b' '格式为我们提供十六进制值的字符串:

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: 因此,代码通过遍历file_content并将每一位附加到binary_data将此二进制字符串转换为数字列表(不知道这是否是最好的方法,也不知道为什么它甚至可以工作),因此我们得到了:

[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? 问题是,如何将该列表转换 b''十六进制二进制字符串或其他内容? As you can see, it has \\x values and metadata in plain text there. 如您所见,它具有\\x值和纯文本格式的元数据。 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

Since you're using Python 3, you can do this: 由于您使用的是Python 3,因此可以执行以下操作:

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

Cheers! 干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM