python - 如何将巨大的二进制数据转换为ASCII格式?

标签 python struct python-2.x binascii

我想读取一个包含大量二进制数据的文件。我想把这个二进制数据转换成 ASCII 格式。在开始时,我想读取 2 个字节,表示消息的大小,消息超出了大小。读完整个消息后,再次重复相同的操作,消息大小为 2 个字节,然后是实际消息。

打印输入数据的代码-

with open("abc.dat", "rb") as f:
byte = f.read(1)
i = 0 
while byte:
    i += 1
    print byte+' ',
    byte = f.read(1)
    if i is 80:
        sys.exit()

输入数据(80字节)-

  O  T  C  _  A  _  R  C  V  R                                                            P  V  �  W          �  w              /  �              �  �  '            �  �  &  �  

编辑1- 。 > 使用 hexdump -n200 otc_a_primary_1003_0600.dat 命令输出-

0000000 4f03 4354 415f 525f 5643 0052 0000 0000
0000010 0000 0000 0000 0000 0000 0000 0000 0000
0000020 0000 0000 0000 0000 5650 57f2 0000 0000
0000030 77d1 0002 0000 0000 902f 0004 0000 0000
0000040 a2bd 1027 0000 0000 d695 e826 2e0b 3e11
0000050 aa55 0300 f332 0000 0046 0000 0000 0000
0000060 5650 57f2 0000 0000 22f8 0a6c 0000 0000
0000070 3030 3030 3730 3435 5135 0000 0000 0100
0000080 bdb4 0100 3000 5131 5a45 1420 077a 9c11
0000090 3591 1416 077a 9c11 dc8d 00c0 0000 0000
00000a0 0000 4300 5241 2020 7f0c 0700 ed0d 0700
00000b0 2052 2020 2030 aa55 0300 f332 0000 0046
00000c0 0000 0000 0000 5650                    
00000c8

我正在使用 python 的 struct模块。 python 版本 - python 2.7.6

程序代码-

import struct

msg_len = struct.unpack('h', f.read(2))[0]
msg_data = struct.unpack_from('s', f.read(msg_len))[0]
print msg_data

但我看不到实际的消息,控制台上仅打印单个字符。我如何以适当的方式读取这样的二进制文件的消息?

最佳答案

这取决于您的两个字节长度如何存储在数据中,例如,如果文件的前两个字节(十六进制)是00 01,这是否意味着后面的消息是1 字节长还是 256 字节长?这称为大端格式或小端格式。尝试以下两种方法,其中一种应该给出更有意义的结果,它旨在读取消息长度 block 中的数据:

大端格式

import struct

with open('test.bin', 'rb') as f_input:
    length =  f_input.read(2)

    while len(length) == 2:
        print f_input.read(struct.unpack(">H", length)[0])
        length =  f_input.read(2)

小端格式

import struct

with open('test.bin', 'rb') as f_input:
    length =  f_input.read(2)

    while len(length) == 2:
        print f_input.read(struct.unpack("<H", length)[0])
        length =  f_input.read(2)

实际数据需要进一步处理。 H 告诉结构体将 2 个字节作为 无符号短整型 进行处理(即该值永远不能被视为负数)。

还需要考虑的一点是,有时长度包括自身,因此长度 2 可能意味着一条空消息。

关于python - 如何将巨大的二进制数据转换为ASCII格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39994357/

相关文章:

python - 您可以将列表附加到字典吗?

python - 属性错误 : __exit__ with socketserver on python-3. 4.3

c - 在C中实现2个具有相同类型和名称但参数不同的函数

python - 关于如何通过 Python 装饰器传递参数的困惑

python - 如何在 Python2.7.10 中使用 multiprocessing 创建子进程而不让子进程与父进程共享资源?

python - 获取 psycopg2 count(*) 个结果

python - 如何在我自己的模板中使用内置的密码重置/更改 View

c++ - C 或 C++ 中位域的最大大小?

go - 在访问未定义的数组元素的结构类型时出错(类型[] ParentIDInfo没有字段或方法PCOrderID)

python - 在 python 中使用多个参数 print-function 时的额外括号和撇号