Convert int32 to int8 with numpy view

Viewed 4470

I tried to view a numpy int32 array as int8 type.

>>> 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)

I expect to convert 1 to [0, 0, 0, 1], but why it turns out to be [1, 0, 0, 0]? Is this related to how the number is stored in memory?

Thanks.

2 Answers

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

Yes, there is big endian and low endian. To quote Wikipedia:

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).

However, you can decide which one you want by using < 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)

Without the < or > it will use the systems endianness. Using a different one can lead to (slight) performance degradation.

Exactly; supposing a low-endian byte ordering, the lowest significant byte of each 32 number will come first, and the most significant will come last. So, DEADBEEF (hex) will become EF BE AD DE.

Related