首页 > 解决方案 > 为什么 numpy 视图是向后的?

问题描述

import numpy as np
data = np.array([0, 0, 0, 0, 0, 0, 0, 1], dtype=np.uint8)
data.view(np.uint64)

我期望的是二进制文件是:

0b0000000000000000000000000000000000000000000000000000000000000001

但相反,8 位组是相反的。

np.array([72057594037927936], dtype=np.uint64)

这是:

0b0000000100000000000000000000000000000000000000000000000000000000

这是为什么?是否正在进行计算来逆转这一点,或者这只是布局?

标签: pythonnumpy

解决方案


您的假设对于数组中二进制数据的顺序是正确的。uint64您可以查看为 8 个字节(V8dtype) ,而不是查看 as :

import numpy as np
np.array([0, 0, 0, 0, 0, 0, 0, 1], dtype=np.uint8).view('V8')[0]
# void(b'\x00\x00\x00\x00\x00\x00\x00\x01')

但是,您的 CPU 使用字节的小端顺序来表示整数。这意味着当将字节查看为 时uint64,您会得到一个非常大的数字。

您可以使用struct包进行如下检查:

import struct
import sys

print(sys.bybteorder)
# 'little'

# view these bytes as uint64 with little endian gives a big number
struct.unpack('<Q', b'\x00\x00\x00\x00\x00\x00\x00\x01')[0]
# 72057594037927936

# view these bytes as uint64 with big endian gives 1
struct.unpack('>Q', b'\x00\x00\x00\x00\x00\x00\x00\x01')[0]
# 1

# view these bytes as uint64 with native endian gives a big number with your CPU
struct.unpack('=Q', b'\x00\x00\x00\x00\x00\x00\x00\x01')[0]
# 72057594037927936

推荐阅读