从二进制文件创建16位和24位整数 [英] Creating 16 and 24-bit integers from binary file

查看:98
本文介绍了从二进制文件创建16位和24位整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在修改一个读取二进制文件的现有Python应用程序.文件格式有些变化.当前,一个字段被定义为记录的字节35-36.规范还指出记录中的...字段将是用ASCII编写的字符字段".这是当前工作代码的样子:

I'm modifying an existing Python app that reads a binary file. The format of the file is changing a bit. Currently, one field is defined as bytes 35-36 of the record. The specs also state that "...fields in the records will be character fields written in ASCII." Here's what the current working code looks like:

def to_i16( word ):
    xx = struct.unpack( '2c', word )
    xx = ( ord( xx[ 0 ] ) << 8 ) + ord( xx[ 1 ] )

    return xx

val = to_i16( reg[ 34:36 ] )

但是该字段被重新定义为35-37字节,因此它将是24位值.我讨厌使用二进制文件,并且在比特纠缠中感到恐惧.如何将3字节值转换为24位整数?我已经尝试了一些通过谷歌搜索找到的代码位,但是我认为它们是不正确的.很难确定,因为我仍在等待发送示例新格式"文件的人员向我发送文本表示形式,以显示应该输入的值.

But that field is being redefined as a bytes 35-37, so it'll be a 24-bit value. I detest working with binary files and am horrible at bit-twiddling. How do I turn that 3-byte value into a 24-bit integer?? I've tried a couple of code bits that I've found by googling but I don't think they are correct. Hard to be sure since I'm still waiting on the people that sent the sample 'new format' file to send me a text representation that shows the values I should be coming up with.

推荐答案

只需读取24位(我假设在大尾数法,因为原始代码也采用这种格式):

Simply read 24 bit (I assume in big endian, since the original code is in that format as well ):

val = struct.unpack('>I', b'\x00' + reg[34:37])

这篇关于从二进制文件创建16位和24位整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆