在python中读取24位二进制数据不起作用

use*_*783 0 python

我使用matlab 将单值(val = 2)写为24位数据:

fid = fopen('.\t1.bin'), 'wb');
fwrite(fid, val, 'bit24', 0);
Run Code Online (Sandbox Code Playgroud)

在bin查看器中,我可以看到数据(值2)存储为02 00 00.我需要在python中将值读取为单个整数.我的代码不起作用:

    struct_fmt = '=xxx'       
    struct_unpack = struct.Struct(struct_fmt).unpack_from
    with open('.\\t1.bin', mode='rb') as file:
        fileContent = file.read()                
        res = struct_unpack(fileContent)
Run Code Online (Sandbox Code Playgroud)

我也试过了

val = struct.unpack('>I',fileContent)
Run Code Online (Sandbox Code Playgroud)

但它给出了错误:

unpack需要长度为4的字符串参数

我究竟做错了什么?
谢谢

bgp*_*ter 6

在Python结构模块格式的字符,x被定义为一个填充字节.你在那里的格式字符串表示读取3个字节,然后丢弃它们.

还没有一个格式说明符来处理24位数据,所以自己构建一个:

>>> def unpack_24bit(bytes):
...    return bytes[0] | (bytes[1] << 8) | (bytes[2] << 16)
...
>>> bytes
'\x02\x00\x00'
>>> unpack_24bit(struct.unpack('BBB', bytes))
2
Run Code Online (Sandbox Code Playgroud)