Skip to main content
 首页 » 编程设计

python之将 24 位整数转换为 32 位整数的更多 Pythonic 方式

2025年01月19日12langtianya

我目前使用以下代码将表示小尾数法带符号的 24 位整数的字节数组转换为带符号的 32 位整数列表。

xs = list(bytes_object) 
ys = [xs[x:x+3] + [255] if xs[x+2] & 128 else xs[x:x+3] + [0] 
      for x in range(0, len(xs), 3)] 
int32s = [struct.unpack('<i', bytes(y))[0] for y in ys] 

是否有更 pythonic 或更有效的方法来处理转换?

请您参考如下方法:

在我的脑海中,是这样的:

import numpy as np 
 
# First convert the buffer to an array of 3-vectors of uint8s 
a3 = np.frombuffer(x, dtype=np.uint8).reshape(-1, 3) 
 
# Now sign-extend it to an array of 4-vectors of uint8s 
signs = (a3[..., 0] > 0x80) * 0xFF 
a4 = np.concatenate((signs.reshape(-1, 1), a), axis=1) 
 
# Now convert that to an array of int32s 
i = a4.view(np.int32) 
 
# And what you eventually wanted to do was convert to float64? 
f = i.astype(np.float64) 

我确定我至少犯了一个错误(这肯定不会在大端系统上工作,至少),而且我面前没有安装 numpy 的计算机,但是希望这能让你开始。无需在 Python 循环中执行任何操作。