从字节中获取位:
bytes = bytes([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
bits = numpy.unpackbits(bytes)
抛出此错误:
类型错误:需要无符号字节数据类型的输入数组
但如果我以这种方式获取字节,它就会起作用:
bytes = numpy.fromfile(filename, dtype="uint8")
如何解决这个错误,谢谢。
最佳答案
您必须传递一个 dtype
为无符号整数的数组:
hex_codes = 0x13, 0x00, 0x00, 0x00, 0x08, 0x00
arr = np.array(hex_codes).astype(np.uint8)
np.unpackbits(arr)
输出:
array([0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0], dtype=uint8)
顺便说一句,您可能知道这一点,但您不应该像使用 bytes
那样重新分配内置函数。
关于python - 尝试将字节转换为位时 Numpy unpackbits 类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70878351/