Home > Net >  "Pack" a np.array of 4 np.uint16 into a single np.unit64
"Pack" a np.array of 4 np.uint16 into a single np.unit64

Time:03-18

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

CodePudding user response:

Here's a solution:

output = np.bitwise_or.reduce(input << (np.arange(len(input)) * 16))

Output:

>>> output
281483566710792

(Side-note: don't use names of Python builtins (e.g. input) as a variable names. :)

CodePudding user response:

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.

  • Related