【问题标题】:Binary to ASCII in PythonPython中的二进制到ASCII
【发布时间】:2016-05-05 23:04:01
【问题描述】:

我正在尝试解码位于 .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?

【问题讨论】:

  • 哦,是的 :-) 对不起。有没有什么简单的方法可以将 .txt 文件中的二进制文件输出为 ASCII 码?
  • 您的意见是什么?预期的输出是多少?这听起来比你想象的要容易。
  • 您的答案是here。只需根据您的需要进行修改即可。
  • 你不能用int("01000001', 2)转换成整数然后chr(65)得到char吗?
  • 您可以使用binintchr 在二进制、ascii 和字符串之间进行转换。

标签: python binary ascii


【解决方案1】:

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

如果是这样,您不需要字典:

def byte_to_char(input):
     return chr(int(input, base=2))

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

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'

【讨论】:

  • 谢谢,但我认为需要一个字典来保存二进制字符串和 ascii 字符之间的映射?这是二进制:0101010010091C1008101,0001,0091,0001,0001,0001,0001,0001,0001,0001,0001,0001,0001,0001,0001,0001,0001,0001,0001,0001,0001,0001,0001,0001,00010101,0001,0001,0001,0001,0001,0001,0001,0001,0001,0001,0001,0001,00010101001,00010101,0001,0001,0001,0001,0001,000101,0001,0001,0001,0001,0001,0001,000101,0001,0001,0001,0001,000100c100100800c>>>>>>>>>跨
  • 这是个问题吗?不,你不需要它。您将二进制字符串转换为整数,然后将该整数转换为 ascii。
  • 谢谢,但二进制字符串位于上述文件夹中的外部文件中。
  • 所以?只需加载该字符串。
  • 所以它会... def code(): bin = int('0b110100001100101011011000110110001101111', 2) pass
猜你喜欢
  • 2011-05-30
  • 1970-01-01
  • 2014-01-14
  • 1970-01-01
  • 1970-01-01
  • 2017-06-10
  • 2018-11-05
  • 2012-08-02
  • 2011-05-12
相关资源
最近更新 更多