【问题标题】:Converting binary timestamp to string将二进制时间戳转换为字符串
【发布时间】:2014-07-06 13:14:38
【问题描述】:

我正在尝试使用 python 解析专有的二进制格式 (Wintec NAL)。有现有的和工作的 C 代码可以做同样的事情(作者:Dennis Heynlein),我正在尝试将其移植到 Python。

我很难理解部分 C 代码。下面是 C 中二进制格式的定义:

/*
 * File extension:. NAL
 * File format: binary, 32 byte fixed block length
 */

/*
 * For now we will read raw structs direct from the data file, ignoring byte
 * order issues (since the data is in little-endian form compatible with i386)
 *
 * XXX TODO:  write marshalling functions to read records in the proper
 * byte-order agnostic way.
 */
#pragma pack (1)

typedef struct nal_data32 {
  unsigned char point_type; /* 0 - normal, 1 - start, 2 - marked */

  unsigned char padding_1;

  unsigned int second: 6, minute: 6, hour: 5;
  unsigned int day: 5, month: 4, year: 6; /* add 2000 to year */

  signed int latitude;    /* divide by 1E7 for degrees */
  signed int longitude;   /* divide by 1E7 for degrees */

  unsigned short height;    /* meters */

  signed char temperature;  /* °C */

  unsigned short pressure;  /* mbar */

  unsigned char cadence;    /* RPM */
  unsigned char pulse;    /* BPM */

  signed char slope;    /* degrees */

  signed short compass;   /* °Z axis */
  signed short roll;    /* °X axis */
  signed short yaw;   /* °Y axis */

  unsigned char speed;    /* km/h */

  unsigned char bike;   /* ID# 0-3 */

  unsigned char padding_2;
  unsigned char padding_3;
} nal_t;

我正在使用 python-bitstring 在 Python 中复制此功能,但我很难理解上面给出的时间格式并将其应用于 Python。

from bitstring import ConstBitStream
nal_format=('''
    uint:8,
    uint:8,
    bin:32,
    intle:32,
    intle:32,
    uint:16,
    uint:8,
    uint:16,
    uint:8,
    uint:8,
    uint:8,
    uint:16,
    uint:16,
    uint:16,
    uint:8,
    uint:8,
    uint:8,
    uint:8
''')

f = ConstBitStream('0x01009f5a06379ae1cb13f7a6b62bca010dc703000000c300fefff9ff00000000')
f.pos=0

#type,padding1,second,minute,hour,day,month,year,lat,lon,height,temp,press,cad,pulse,slope,compass,roll,yaw,speed,bike,padding2,padding3=f.peeklist(nal_format)

type,padding1,time,lat,lon,height,temp,press,cad,pulse,slope,compass,roll,yaw,speed,bike,padding2,padding3=f.readlist(nal_format)

print type
print padding1
#print second 
#print minute
#print hour
#print day
#print month
#print year
print time
print lat
print lon

虽然我发现必须将纬度和经度定义为 little-endian,但我不知道如何调整 32 位宽的时间戳,使其符合 C 定义中给出的格式(而且我也不能t 为“height”找出一个匹配的掩码 - 相应地我没有尝试它之后的字段。

这些是上面十六进制字符串的值:

  • 日期:2013/12/03-T05:42:31
  • 位置:73.3390583° E,33.2128666° N
  • 罗盘:195°,滚动 -2°,偏航 -7°
  • 海拔高度:458 米
  • 温度:13°C
  • 压力:967 mb

【问题讨论】:

    标签: python c binary endianness bitstring


    【解决方案1】:

    我不熟悉bitstring,所以我会将您的输入转换为打包的二进制数据,然后使用struct 进行处理。如果您对该部分不感兴趣,请跳到休息时间。

    import binascii
    
    packed = binascii.unhexlify('01009f5a06379ae1cb13f7a6b62bca010dc703000000c300fefff9ff00000000')
    

    如果您愿意,我可以更详细地介绍这部分。它只是将'0100...' 变成b'\x01\x00...'

    现在,解包时唯一的“问题”是确定您只想解包 ONE unsigned int,因为该位字段适合 32 位(单个 unsigned int 的宽度):

    format = '<ccIiiHbHBBbhhhBBBB'
    
    import struct
    
    struct.unpack(format,packed)
    Out[49]: 
    ('\x01',
     '\x00',
    923163295,
    ...
    )
    

    这会将输出转换为我们可以使用的输出。您可以像以前一样将其解压缩到一长串变量中。


    现在,您的问题似乎集中在如何屏蔽 time(上图:923163295)以从位字段中获取正确的值。这只是一点点数学:

    second_mask = 2**6 - 1
    minute_mask = second_mask << 6
    hour_mask = (2**5 - 1) << (6+6)
    day_mask = hour_mask << 5
    month_mask = (2**4 - 1) << (6+6+5+5)
    year_mask = (2**6 - 1) << (6+6+5+5+4)
    
    time & second_mask
    Out[59]: 31
    
    (time & minute_mask) >> 6
    Out[63]: 42
    
    (time & hour_mask) >> (6+6)
    Out[64]: 5
    
    (time & day_mask) >> (6+6+5)
    Out[65]: 3
    
    (time & month_mask) >> (6+6+5+5)
    Out[66]: 12
    
    (time & year_mask) >> (6+6+5+5+4)
    Out[67]: 13L
    

    在函数形式上,整体更自然一点:

    def unmask(num, width, offset):
         return (num & (2**width - 1) << offset) >> offset
    

    哪个(现在我想起来了)重新排列成:

    def unmask(num, width, offset):
         return (num >> offset) & (2**width - 1)
    
    unmask(time, 6, 0)
    Out[77]: 31
    
    unmask(time, 6, 6)
    Out[78]: 42
    
    #etc
    

    如果你想变得花哨,

    from itertools import starmap
    from functools import partial
    
    width_offsets = [(6,0),(6,6),(5,12),(5,17),(4,22),(6,26)]
    
    list(starmap(partial(unmask,time), width_offsets))
    Out[166]: [31, 42, 5, 3, 12, 13L]
    

    正确格式化所有这些数字,最后得出预期的日期/时间:

    '20{:02d}/{:02d}/{:02d}-T{:02d}:{:02d}:{:02d}'.format(*reversed(_))
    Out[167]: '2013/12/03-T05:42:31'
    

    (可能有一种方法可以用 bitstring 模块优雅地完成所有这些按位数学运算,但我只是觉得从第一原理解决问题很令人满意。)

    【讨论】:

    • 我知道位域,这就是我从结构切换到位串的原因,因为我认为它可以让我拆分位域的时间元素。但最终我仍然无法弄清楚如何处理位域,因为简单地拆分位是行不通的。感谢您对所涉及的数学的解释,我得到了它的工作 - 我永远无法自己解决这个问题:-)
    【解决方案2】:

    “C”结构中的时间戳是一个“C”位域。编译器使用冒号后的数字在较大的字段定义中分配一些位。在这种情况下,一个无符号整数(4 个字节)。查看here 以获得更好的解释。对于位字段,最大的问题是位是根据计算机的字节序类型分配的,因此它们不是很便携。

    您的 Python 格式声明中似乎存在错误。它可能应该为该日期分配一个额外的 4 字节 unsigned int。比如:

    nal_format=('''
        uint:8,
        uint:8,
        bin:32,
        bin:32,
        intle:32,
        intle:32,
    ''')
    

    要在 Python 中表示位字段,请使用 Python 位数组来表示位。查看this

    还有一点需要注意,结构上的 pack(1)。它告诉编译器在一个字节边界上对齐。换句话说,不要在字段之间添加任何填充。通常对齐是 4 字节,导致编译器在 4 字节边界上开始每个字段。更多信息请查看here

    【讨论】:

    • 不,不需要额外的无符号整数,他的格式规范是正确的。位字段中的所有位加起来为 32,因此它适合单个无符号整数。
    • 感谢您的指点和链接!我的主要问题是时间戳位域所需的二进制计算 - @roippi 在他的回答中详细解释了这一点。
    • 感谢@roippi 的指正。您对位的位置是正确的。
    猜你喜欢
    • 2020-11-22
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多