Skip to main content
 首页 » 编程设计

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

2025年05月04日14xiaohuochai

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(),即使它有点难看.