Python中的二进制到ASCII

时间:2016-01-28 14:07:45

标签: 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

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

1 个答案:

答案 0 :(得分:6)

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

如果是这样,你就不需要这个词典了:

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)]

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

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'