【问题标题】:reading binary data byte wise and extract data using python逐字节读取二进制数据并使用python提取数据
【发布时间】:2018-12-04 18:34:27
【问题描述】:

我有一个包含以下内容的文件:

 0:   10 51 03 37 7F 43 82 99  45 3F E7 35 3A A8 80 B9   .text ? etc  # text 
10:   3D 3F F4 49 F8 9A 7A 85  03 40 8A C8 46 DE 0A 1A   . -@ =! ETC  # text 
30:   .......................................................
40:   ...........................................10 03

     Repeat next instant 
     10 51 ................................................................
     ............................................ 10 03

这是一条消息,其中 10 和 51 表示特定消息的开始,而 10 03 表示消息的结束。 10表示0字节位置,51表示1字节位置并继续。

我的目标是读取 5-8 字节位置十六进制数据并转换为浮点数和 9-16 位置字节以在每个瞬间加倍

到目前为止,我的实现只读取前 31 个十六进制数据。

 import struct

with open("RawData.log",'rb') as fin:
    data1 = ["{:02x}".format(ord(c)) for c in fin.read()]
    data2=''.join(data1)

    #data=pd.DataFrame({'test':data1})
    header = "51"
    tail   = "03"


   # header_index = data2.index(header)
    header_index=[i for i, s in enumerate(data1) if header in s]
    footer_index = [i for i, s in enumerate(data1) if tail  in s]
    if header_index >= 0 and footer_index >= header_index:
       body = data2[10:18]
       print struct.unpack('!f',body.decode('hex'))[0]

       #261.197418213 only 1 output not iterating for whole file. Similarly how to extract 9 to 16 byte position data to double for entire file.

如何读取整个文件并在每次找到消息头时仅从十六进制数据中提取这两个字段(10 和 51)

【问题讨论】:

    标签: python python-2.7 file binary hex


    【解决方案1】:

    这是一种提取分隔符之间的数据并从文件中每条消息的前 12 个位置解压缩浮点数和双精度数的简单方法:

    with open('RawData.log', 'rb') as f:  # read data in binary format
        bs = f.read()
    prev = None
    start = None
    end = None
    for i, b in enumerate(bs):
        if prev == b'\x10' and b == b'\x51':
            # match beginning of message
            start = i + 1 
        if prev == b'\x10' and b == b'\x03':
            # match end of message
            end = i - 1 
        if start and end:
            data = bs[start:end]
            fmt = '!fd'   # unpack a float and double, big-endian
            flt, dble = struct.unpack(fmt, data[:12])
            print flt, dble
            # reset delimiter positions
            start = None
            end = None
        prev = b 
    

    【讨论】:

    • 感谢您的回复。我会检查您的解决方案并检查。
    • 它给出错误“解包需要长度为 12 的字符串参数”
    • data[:12] 的唯一方法是len(data) < 12,在这种情况下它不能包含浮点数和双精度数。您的问题中是否缺少某些信息,或者这只是您需要处理的文件中的错误?
    • 你能告诉我这里 12 是什么意思吗?我尝试了不同的方式,能够提取字节位置 5 到 8 的数据,但不能提取整个文件的数据。请检查我的帖子。我又编辑了
    猜你喜欢
    • 2011-07-27
    • 2010-12-08
    • 2013-12-06
    • 1970-01-01
    • 2013-03-23
    • 2017-07-10
    • 1970-01-01
    • 2019-02-11
    相关资源
    最近更新 更多