如何将大量二进制数据转换成ASCII格式?

2024-10-03 23:28:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我想读一个包含大量二进制数据的文件。我想把这个二进制数据转换成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字节)—

^{pr2}$

编辑1- . >; 输出ussing 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

但我看不到真正的消息,控制台上只有一个字符在打印。如何以适当的方式读取这种二进制文件的消息?在


Tags: 文件数据消息readlen字节二进制msg
3条回答

docs

For the 's' format character, the count is interpreted as the size of the string, not a repeat count like for the other format characters; for example, '10s' means a single 10-byte string, while '10c' means 10 characters. If a count is not given, it defaults to 1. For packing, the string is truncated or padded with null bytes as appropriate to make it fit. For unpacking, the resulting string always has exactly the specified number of bytes. As a special case, '0s' means a single, empty string (while '0c' means 0 characters).

's'应修改为str(msg_len)+'s'。提前检查msg_len是否合理是个好主意。在

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

大端格式

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)

Little-endian格式

^{pr2}$

实际数据需要进一步处理。H告诉struct将这2个字节作为unsigned short处理(即,该值永远不能被认为是负的)。在

另一个需要考虑的问题是,有时长度包含自身,因此长度为2可能意味着一条空消息。在

尝试:

import struct

with open('abc.dat', 'rb') as f:
    while True:
        try:
            msg_len = struct.unpack('h', f.read(2))[0] # assume native byte order
            msg_data = f.read(msg_len) # just read 'msg_len' bytes
            print repr(msg_data)
        except:
            # something wrong or reach EOF
            break

相关问题 更多 >