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

2024-10-01 09:41:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我用matlab将单个值(val=2)写成24位数据,如下所示:

fid = fopen('.\t1.bin'), 'wb');
fwrite(fid, val, 'bit24', 0);

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

^{pr2}$

我也试过了

val = struct.unpack('>I',fileContent)

但它给出了错误:

unpack requires a string argument of length 4

我做错什么了?
谢谢
赛迪


Tags: 数据代码bin整数val中将t1wb
2条回答

在Python结构模块format characters中,x被定义为pad字节。这里的格式字符串表示读取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

通过访问单个字节,可以始终将整数转换为字节,反之亦然。只需要处理好endianness。在

下面的代码使用一个随机整数转换成24位二进制并返回。在

导入结构,随机

# some number in the range of [0, UInt24.MaxValue]
originalvalue = int (random.random() * 255 ** 3)   

# take each one of its 3 component bytes with bitwise operations
a = (originalvalue & 0xff0000) >> 16
b = (originalvalue & 0x00ff00) >> 8
c = (originalvalue & 0x0000ff)

# byte array to be passed to "struct.pack"
originalbytes = (a,b,c)
print originalbytes

# convert to binary string
binary = struct.pack('3B', *originalbytes)

# convert back from binary string to byte array
rebornbytes = struct.unpack('3B', binary)   ## this is what you want to do!
print rebornbytes

# regenerate the integer
rebornvalue = a << 16 | b << 8 | c
print rebornvalue

相关问题 更多 >