np.array of 4
input = np.random.randint(10, size=4, dtype=np.uint16)
how can I "pack" their binary representations into a single
# Example of C code # output = input | input << 16 | input << 32 | input << 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
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.
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)