将二进制字符串转换为二进制
Converts strings of binary to binary
我有一个文本文件,我想以二进制形式读取它,以便将其内容转换为十六进制字符。
然后,我需要将'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)
最后一行产生错误(我不完全理解strings/hex/binary在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
我想您正在寻找这样的东西?参考评论了解我为什么这样做。
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)
我在使用它时注意到的一件事是,使用您的 solution/file,有 2620 位,这并没有分成 8,因此它不能正确地变成字节。
我有一个文本文件,我想以二进制形式读取它,以便将其内容转换为十六进制字符。
然后,我需要将'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)
最后一行产生错误(我不完全理解strings/hex/binary在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
我想您正在寻找这样的东西?参考评论了解我为什么这样做。
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)
我在使用它时注意到的一件事是,使用您的 solution/file,有 2620 位,这并没有分成 8,因此它不能正确地变成字节。