Creating 16 and 24-bit integers from binary file

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-12 01:29:35

问题


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 ] )

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.


回答1:


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])


来源:https://stackoverflow.com/questions/14840120/creating-16-and-24-bit-integers-from-binary-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!