Python – numpy array (10-bit integer) with arbitrary precision

numpy array (10-bit integer) with arbitrary precision… here is a solution to the problem.

numpy array (10-bit integer) with arbitrary precision

I need to emulate a piece of hardware that generates binaries where each word is 10 bits. How can I use numpy arrays for this?

Similar to:

outarray = np.zeros(512, dtype=np.int10)

Thanks!

Solution

Numpy does not have a uint10 type. But you can use uint16 and bitmasks to check for overflow. And use binary_rep to get the 10-bit binary representation:

import numpy as np

MAX_WORD = 2**10
unused_bits = ~np.array([MAX_WORD-1], dtype="uint16")  # Binary mask of the 6 unused_bits

words = np.random.randint(MAX_WORD, size=10, dtype="uint16")  #  Create 10 bit words
assert not np.any(words & unused_bits)  # Check for overflow
for word in words:
    print(word, np.binary_repr(word, width=10))  # Get 10 bit binary representation

binary_repr = "".join(np.binary_repr(word, width=10) for word in words)
print(binary_repr)  # Full binary representation

Related Problems and Solutions