python - 为什么 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
这是为什么?是否正在进行计算来逆转这一点,或者这只是布局?
解决方案
您的假设对于数组中二进制数据的顺序是正确的。uint64
您可以查看为 8 个字节(V8
dtype) ,而不是查看 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
推荐阅读
- mysql - MySQL中复合聚集索引的实现
- r - 在模式后替换字符串 3 - 10 个位置的元素
- swiftui - 恢复应用内购买时出现 StoreKit 问题
- c# - 首选 32 位标志在 ASP.NET .NET Core 中不起作用
- javascript - 节点 js 删除作者并获取书籍以显示所有带有信息的书籍
- c++ - 如何使用智能指针创建和使用单例模式
- python - Odoo 12. 如何覆盖一个被覆盖的函数?
- python - 使用 matplotlib 绘制日期有间隙的数据框
- node.js - Discord.js TypeError:无法读取未定义的属性“大小”
- c# - 在案例声明中传递图像文件 - Razor Pages