【问题标题】:Converts strings of binary to binary将二进制字符串转换为二进制
【发布时间】:2021-02-24 14:24:51
【问题描述】:

我有一个文本文件,想以二进制形式读取它,以便将其内容转换为十六进制字符。

然后,我需要将“20”替换为“0”,将“80”、“e2”、“8f”替换为“1”。

这将创建一个由 0 和 1 组成的字符串(基本上是二进制)。

最后,我需要把这个二进制字符串转换成ascii字符。

我快完成了,但我在最后一部分中挣扎:

import binascii
import sys

bin_file = 'TheMessage.txt'

with open(bin_file, 'rb') as file:
        file_content = file.read().hex()
        file_content = file_content.replace('20', '0').replace('80', '1').replace('e2', '1').replace('8f', '1')

    print(file_content)
    text_bin = binascii.a2b_uu(file_content)

最后一行产生错误(我不完全理解python中的字符串/十六进制/二进制解释):

Traceback (most recent call last):
  File "binary_to_string.py", line 34, in <module>
    text_bin = binascii.a2b_uu(file_content)
binascii.Error: Trailing garbage

你能帮帮我吗?

我正在处理这个文件:blank_file

【问题讨论】:

    标签: python-3.x binary hex ascii


    【解决方案1】:

    我认为您正在寻找这样的东西?请参阅 cmets 了解我为什么这样做。

    import binascii
    import sys
    
    bin_file = 'TheMessage.txt'
    
    with open(bin_file, 'rb') as file:
            file_content = file.read().hex()
            file_content = file_content.replace('20', '0').replace('80', '1').replace('e2', '1').replace('8f', '1')
    
    # First we must split the string into a list so we can get bytes easier.
    bin_list = []
    for i in range(0, len(file_content), 8): # 8 bits in a byte!
        bin_list.append(file_content[i:i+8])
    
    message = ""
    for binary_value in bin_list:
        binary_integer = int(binary_value, 2) # Convert the binary value to base2
        ascii_character = chr(binary_integer) # Convert integer to ascii value
    
        message+=ascii_character
    
    print(message)
    

    我在处理这个问题时注意到的一件事是,使用您的解决方案/文件,有 2620 位,并且这不分为 8,所以它不能正确地变成字节。

    【讨论】:

    • 哦,是的,我忘了分成 8 位!谢谢大佬,这就是我要找的。也感谢2620bit的评论!
    • 没问题老兄:)
    猜你喜欢
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    • 2012-10-05
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多