gpt4 book ai didi

python - 使用 numpy View 将 int32 转换为 int8

转载 作者:太空宇宙 更新时间:2023-11-03 14:50:13 26 4
gpt4 key购买 nike

我试图将一个 numpy int32 数组视为 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]?这与数字在内存中的存储方式有关吗?

谢谢。

最佳答案

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)

没有 <>它将使用系统字节序。使用不同的可能会导致(轻微的)性能下降。

关于python - 使用 numpy View 将 int32 转换为 int8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46352117/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com