我正在尝试解码位于 .txt 文件中的二进制文件,但我卡住了。我看不出有任何可能解决这个问题。
def code(): testestest
ascii = {'01000001':'A', ...}
binary = {'A':'01000001', ...}
print (ascii, binary)
def encode():
pass
def decode(code,n):
f = open(code, mode='rb') # Open a file with filename <code>
while True:
chunk = f.read(n) # Read n characters at time from an open file
if chunk == '': # This is one way to check for the End Of File in Python
break
if chunk != '\n':
# Process it????
pass
如何获取 .txt 文件中的二进制文件并将其输出为 ASCII?
请您参考如下方法:
从您的示例来看,您的输入看起来像是二进制格式数字的字符串。
如果是这样,你不需要字典:
def byte_to_char(input):
return chr(int(input, base=2))
使用您在评论中提供的数据,您必须将二进制字符串拆分为字节。
input ='01010100011010000110100101110011001000000110100101110011001000000110101001110101011100110111010000100000011000010010000001110100011001010111001101110100001000000011000100110000001110100011000100110000'
length = 8
input_l = [input[i:i+length] for i in range(0,len(input),length)]
然后,将每个字节转换成一个字符:
input_c = [chr(int(c,base=2)) for c in input_l]
print ''.join(input_c)
综合起来:
def string_decode(input, length=8):
input_l = [input[i:i+length] for i in range(0,len(input),length)]
return ''.join([chr(int(c,base=2)) for c in input_l])
decode(input)
>'This is just a test 10:10'
