[SOLVED] "Pack" a np.array of 4 np.uint16 into a single np.unit64


Given a np.array of 4 np.uint16

input = np.random.randint(10, size=4, dtype=np.uint16)

how can I "pack" their binary representations into a single np.uint64?

# Example of C code
# output = input[0] | input[1] << 16 | input[2] << 32 | input[3] << 48

The order in which the 4 np.uint16 are packed is not important (provided it’s not random).


You can reinterpret bytes of an array with np.view:

input.view(np.uint64) # 844429225558024 on my x86-64 machine

This does not perform any copy or computation. It is performed quickly and in a constant-time. However, the order of the bytes is architecture-dependent due to the endianness. It is little-endian on most architectures, including x86-64, most ARM processors and recent POWER processors.

Note that input.view(np.uint64).view(np.uint16) is guaranteed to give you the input array here.

Note that regarding the wanted endianness, you can swap the bytes of Numpy arrays.

Answered By – Jérôme Richard

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *