用numpy vi将int32转换为int8

2024-10-03 06:19:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将numpyint32数组看作int8类型。在

>>> a = np.array([1, 2, 3, 4], dtype='int32')
>>> a
array([1, 2, 3, 4], dtype=int32)
>>> a.view('int8')
array([1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0], dtype=int8)

我希望将1转换为[0,0,0,1],但为什么它会变成[1,0,0,0]?这与数字在内存中的存储方式有关吗?在

谢谢。在


Tags: 内存view类型np方式数字数组array
2条回答

Is this related to how the number is stored in memory?

是的,有big endian and low endian。引用维基百科:

Endianness refers to the sequential order in which bytes are arranged into larger numerical values, when stored in computer memory or secondary storage, or when transmitted over digital links. Endianness is of interest in computer science because two conflicting and incompatible formats are in common use: words may be represented in big-endian or little-endian format, depending on whether bits or bytes or other components are ordered from the big end (most significant bit) or the little end (least significant bit).

但是,您可以使用^{} and ^{} in the dtype来决定要哪一个:

>>> import numpy as np
>>> a = np.array([1, 2, 3, 4], dtype='>i4')
>>> a.view('int8')
array([0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4], dtype=int8)

>>> a = np.array([1, 2, 3, 4], dtype='<i4')
>>> a.view('int8')
array([1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0], dtype=int8)

如果没有<>,它将使用系统的endianness。使用另一个可能会导致(轻微)性能下降。在

确切地说,假设一个低位字节排序,那么每个32个数字的最低有效字节将排在第一位,最高有效字节将排在最后。所以,DEADBEEF(十六进制)将变成EF BE AD DE。在

相关问题 更多 >