简体   繁体   中英

Creating 16 and 24-bit integers from binary file

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.

只需读取24位(我假设使用big endian ,因为原始代码也采用这种格式):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM