Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中读取24位二进制数据不起作用_Python - Fatal编程技术网

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

在python中读取24位二进制数据不起作用,python,Python,我使用matlab将单个值(val=2)写成24位数据,如下所示: fid = fopen('.\t1.bin'), 'wb'); fwrite(fid, val, 'bit24', 0); 在bin查看器中,我可以看到数据(值2)存储为02 00。 我需要在python中将值读取为单个整数。 我下面的代码不起作用: struct_fmt = '=xxx' struct_unpack = struct.Struct(struct_fmt).unpack_from

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

fid = fopen('.\t1.bin'), 'wb');
fwrite(fid, val, 'bit24', 0);
在bin查看器中,我可以看到数据(值2)存储为02 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)
我也试过了

val = struct.unpack('>I',fileContent)
但它给出了一个错误:

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

我做错了什么?
谢谢

sedy

在Python结构模块中,
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
def unpack_24位(字节): ... 返回字节[0]|(字节[1]>字节 “\x02\x00\x00” >>>解包\u 24位(结构解包('BBB',字节)) 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
#一些在[0,UInt24.MaxValue]范围内的数字
originalvalue=int(random.random()*255**3)
#使用逐位操作获取其3个组件字节中的每一个
a=(原始值&0xff0000)>>16
b=(原始值&0x00ff00)>>8
c=(原始值和0x0000ff)
#要传递给“struct.pack”的字节数组
原始字节=(a、b、c)
打印原始字节
#转换为二进制字符串
二进制=结构包('3B',*原始字节)
#将二进制字符串转换回字节数组
rebornbytes=struct.unpack('3B',二进制)##这就是您想要做的!
打印重新启动字节
#重新生成整数

rebornvalue=a您得到的错误消息和堆栈跟踪是什么?@BenjaminHodgson嗯,没有错误,但是“res”读取0,而它应该是2个副本?在“duplicate”中的回答不起作用。您总是可以逐字节读取结果,并将其“汇编”为32位值。