Home > Mobile >  How can I convert an integer to its binary representation as a numpy array?
How can I convert an integer to its binary representation as a numpy array?

Time:08-10

I'm interested in taking a single integer and converting it to a numpy array of 1's and 0's equal to the number's binary representation. I'd like to fix the length of the array (pad with zeros as needed) while I'm at it. How can this been done?

Something along these lines:

>>> func(19,bits=7)
np.array([0,0,1,0,0,1,1])

CodePudding user response:

Use Python's bin() for binary conversion

def func(x, bits):
    return np.array([int(i) for i in bin(x)[2:].zfill(bits)])

Explanation

bin(x)[2:] slices the binary-specific prefix from the string representation of the binary data. Subsequently, zfill() appends leading zeros. However, it only does so when the number of bits is sufficient to represent the integer input x as a binary vector. Otherwise, it is neglected. Finally, a list comprehension [int(i) for i in ...] is used as the input to the NumPy array constructor.

The advantage of the implementation is that it does not require to pre-define the range of the integer input or checking for the validity of the number of bits.

  • Related