Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

NumPy Byte Swapping

NumPy Byte Swapping

On almost all machines, multi-byte objects are stored as contiguous sequences of bytes. Byte order is the storage rule for program objects spanning multiple bytes.

For example, in the C language, a variable x of type int has an address of 0x100, so the value of its corresponding address expression &x is 0x100. And the four bytes of x will be stored at positions 0x100, 0x101, 0x102, 0x103 in memory.

numpy.ndarray.byteswap()

The numpy.ndarray.byteswap() function converts the bytes in each element of the ndarray between big-endian and little-endian.

Example

import

numpy

as

np

a

=

np

.

array

(

[

1

,

256

,

8755

]

,

dtype

=

np

.

int16

)

print

(

'

Our array is:

'

)

print

(

a

)

print

(

'

Represent the data in memory in hexadecimal:

'

)

print

(

map

(

hex

,

a

)

)

The byteswap() function swaps in place by passing true

print

(

'

Call the byteswap() function:

'

)

print

(

a

.

byteswap

(

True

)

)

print

(

'

Hexadecimal form:

'

)

print

(

map

(

hex

,

a

)

)

We can see that the bytes have been swapped

The output is:

我们的数组是:

[   1  256 8755]

Display memory data in hexadecimal:



Call the byteswap() function:

[  256     1 13090]

Hexadecimal format: