python - 单个 Numpy 类型似乎不保留字节顺序

标签 python numpy endianness

Numpy 版本:1.6.2

有人可以解释为什么数组的单个标量不维护 dtype 中设置的字节序吗?如何让它们以正确的字节顺序输出?

>>> numpy_type1 = numpy.uint32
>>> numpy_type2 = numpy.dtype(numpy_type1).newbyteorder('>')
>>> hexdump(numpy.array([100000000], dtype = numpy_type1).tostring())
'00e1f505' # OKAY (endianness of host platform)
>>> hexdump(numpy.array([100000000], dtype = numpy_type2).tostring())
'05f5e100' # OKAY (byte swap is visible)
>>> hexdump(numpy.array([100000000], dtype = numpy_type1)[0].tostring())
'00e1f505' # OKAY (endianness of host platform)
>>> hexdump(numpy.array([100000000], dtype = numpy_type2)[0].tostring())
'00e1f505' # FAIL (no byte swapping seen)
>>> hexdump(numpy_type1(100000000).tostring())
'00e1f505' # OKAY (endianness of host platform)
>>> hexdump(numpy_type2.type(100000000).tostring())
'00e1f505' # FAIL (no byte swapping seen)

在上面的示例中,请注意当在 numpy 数组上调用 tostring 时字节交换正确执行,但在数组的标量元素上执行不正确?

简单地说,我只需要一些方法来实例化 dtype 中的值并以正确的字节顺序获取二进制字符串。我不能使用 Python 结构,因为它不支持 float16、float128 或 Numpy 支持的其他奇特数字类型。我不想手动进行字节交换。

我很想看到这个作品:

>>> hexdump(numpy_type2.type(100000000).tostring())
'05f5e100' # OKAY (byte swapping seen)

最佳答案

对于单个值,您也可以使用 struct 包。为简单起见,标量在 numpy(总是系统)中根本没有字节顺序。但是,您也可以使用 0-d 数组来保留字节顺序。但对于大多数结果,numpy 会将 0 维数组转换为标量,因为它们通常是您想要的。

既然你说你不能使用struct,你可以使用np.array(scalar, dtype=original.dtype).tostring(),即使它有点难看.

关于python - 单个 Numpy 类型似乎不保留字节顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13740275/

相关文章:

python - 如何在python中通过文本文件获取输入?

python : 'string index out of range'

python - 非常慢的 Numpy 缓冲区指针访问

python - 使用 scipy.stats 使用自定义分布拟合数据

c++ - 更改 float 字节序的最正确方法是什么

c - 读取二进制文件并正确使用数据

c++ - cpp中的字节序转换

python - 无法注册 Google Assistant 设备型号

python - while 循环计数器比较两个列表

python - 解决 Numpy 中的广义特征值问题