numpy.ndarray.byteswap#

方法

ndarray.byteswap(inplace=False)#

交換陣列元素的位元組

透過傳回位元組交換後的陣列,在小端序和大端序資料表示法之間切換,可選擇是否就地交換。位元組字串陣列不會被交換。複數的實部和虛部會個別交換。

參數:
inplacebool,選用

True,則就地交換位元組,預設為 False

傳回值:
outndarray

位元組交換後的陣列。若 inplaceTrue,則此為 self 的檢視。

範例

>>> import numpy as np
>>> A = np.array([1, 256, 8755], dtype=np.int16)
>>> list(map(hex, A))
['0x1', '0x100', '0x2233']
>>> A.byteswap(inplace=True)
array([  256,     1, 13090], dtype=int16)
>>> list(map(hex, A))
['0x100', '0x1', '0x3322']

位元組字串陣列不會被交換

>>> A = np.array([b'ceg', b'fac'])
>>> A.byteswap()
array([b'ceg', b'fac'], dtype='|S3')

A.view(A.dtype.newbyteorder()).byteswap() 產生一個具有相同值但在記憶體中表示法不同的陣列

>>> A = np.array([1, 2, 3],dtype=np.int64)
>>> A.view(np.uint8)
array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
       0, 0], dtype=uint8)
>>> A.view(A.dtype.newbyteorder()).byteswap(inplace=True)
array([1, 2, 3], dtype='>i8')
>>> A.view(np.uint8)
array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
       0, 3], dtype=uint8)