【问题标题】:ascii txt file to binary bin fileascii txt 文件到二进制 bin 文件
【发布时间】:2013-11-01 13:44:11
【问题描述】:

我有一个包含 HEX 数据流的 txt 文件,我想将其转换为二进制格式以节省磁盘空间。

这是我的简单脚本,只是为了测试解码和二进制存储

hexstr = "12ab"

of = open('outputfile.bin','wb')

for i in hexstr:
    #this is how I convert an ASCII char to 7 bit representation 
    x = '{0:07b}'.format(ord(i))
    of.write(x)

of.close()

我希望 outputfile.bin 的大小为 28 位,而不是结果为 28 字节。 我想问题是 x 是一个字符串而不是一个位序列。

我该怎么办?

提前致谢

【问题讨论】:

  • 是的,python 的filobject.write 需要一个字符串,所以它可能也将它写成一个字符串。
  • 我认为 binascii 模块可能是您正在寻找的......
  • 你看到this的问题了吗?请注意,为每个 ASCII 字符存储 7 位只会为每 8 个字符节省 1 个八位字节 - 可能更少,具体取决于您的文件系统。
  • 什么是“十六进制数据流”“带有 HEX 数据流的 txt 文件”是什么意思

标签: python file python-2.7 binary


【解决方案1】:

首先,在任何流行平台上,您都不会得到不是 8 位倍数的文件大小。

其次,您确实必须重新了解“二进制”的实际含义。您混淆了两个不同的概念:表示二进制数系统中的数字和以“非人类可读”形式写出数据。

实际上,您混淆了两个更基本的概念:数据和数据的表示。 "12ab" 是内存中四个字节的表示,"\x31\x32\x61\x62" 也是如此。

您的问题是 x 包含 28 个字节的数据,可以表示为 "0110001011001011000011100010" 或“\x30\x31\x31\x30\x30...\x30\x30\x31\x30"”。

也许这会对你有所帮助:

>>> hexstr = "12ab"
>>> len(hexstr)
4
>>> ['"%s": %x' % (c, ord(c)) for c in hexstr]
['"1": 31', '"2": 32', '"a": 61', '"b": 62']

>>> i = 42
>>> hex(i)
'0x2a'
>>> x = '{0:07b}'.format(i)
>>> x
'0101010'
>>> [hex(ord(c)) for c in x]
['0x30', '0x31', '0x30', '0x31', '0x30', '0x31', '0x30']
>>> hex(ord('0')), hex(ord('1'))
('0x30', '0x31')

>>> import binascii
>>> [hex(ord(c)) for c in binascii.unhexlify(hexstr)]
['0x12', '0xab']

也就是说,binascii 模块有一个可以使用的方法:

import binascii

data = binascii.unhexlify(hexstr)
with open('outputfile.bin', 'wb') as f:
    f.write(data)

这会将您的数据编码为 8 位而不是 7 位,但出于压缩原因,通常不值得使用 7 位。

【讨论】:

  • 感谢您的解决方案,它比我预期的要多!是的...我必须审查“二进制”的含义
【解决方案2】:

这是你想要的吗? “12ab”应该写成\x01\x02\x0a\x0b吧?

import struct

hexstr = "12ab"

of = open('outputfile.bin','w')

for i in hexstr:
    of.write(struct.pack('B', int(i, 16)))

of.close()

【讨论】:

  • 你也可以使用chr(int(i, 16))
  • 其实在7位编码中,'12ab'应该写成\xC5\x96\x1C\x40
  • @MichaelFoukarakis 我不明白你的意思。文字 '\xC5' 是一个十六进制整数 (docs.python.org/2/reference/…)
猜你喜欢
  • 2015-04-08
  • 2013-05-09
  • 1970-01-01
  • 2020-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-13
  • 1970-01-01
相关资源
最近更新 更多