[英]Creating 16 and 24-bit integers from binary file
I'm modifying an existing Python app that reads a binary file. 我正在修改一个现有的读取二进制文件的Python应用程序。 The format of the file is changing a bit.
文件的格式有些变化。 Currently, one field is defined as bytes 35-36 of the record.
当前,一个字段被定义为记录的字节35-36。 The specs also state that "...fields in the records will be character fields written in ASCII."
规范还指出“记录中的...字段将是用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 ] )
But that field is being redefined as a bytes 35-37, so it'll be a 24-bit value. 但是该字段被重新定义为35-37字节,因此它将是24位值。 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??
如何将3字节值转换为24位整数? 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位(我假设使用big endian ,因为原始代码也采用这种格式):
val = struct.unpack('>I', b'\x00' + reg[34:37])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.