Python中的二进制到ASCII

Mus*_*usa 1 python binary ascii

我正在尝试解码位于.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
Run Code Online (Sandbox Code Playgroud)

如何获取.txt文件中的二进制文件并将其输出为ASCII?

tgl*_*ria 6

从您的示例中,您的输入看起来像二进制格式化数字的字符串.

如果是这样,你不需要一个字典:

def byte_to_char(input):
     return chr(int(input, base=2))
Run Code Online (Sandbox Code Playgroud)

使用您在注释中提供的数据,您必须将二进制字符串拆分为字节.

input ='01010100011010000110100101110011001000000110100101110011001000000110101001110101011100110111010000100000011000010010000001110100011001010111001101110100001000000011000100110000001110100011000100110000'
length = 8
input_l = [input[i:i+length] for i in range(0,len(input),length)]
Run Code Online (Sandbox Code Playgroud)

然后,每个字节,您将其转换为char:

input_c = [chr(int(c,base=2)) for c in input_l]
print ''.join(input_c)
Run Code Online (Sandbox Code Playgroud)

把它们放在一起:

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'
Run Code Online (Sandbox Code Playgroud)