Built-in function in numpy to interpret an integer to an array of boolean values in a bitwise manner?

StackOverflow https://stackoverflow.com/questions/22773443

  •  25-06-2023
  •  | 
  •  

Question

I'm wondering if there is a simple, built-in function in Python / Numpy for converting an integer datatype to an array/list of booleans, corresponding to a bitwise interpretation of the number please?

e.g:

x = 5 # i.e. 101 in binary
print FUNCTION(x)

and then I'd like returned:

[True, False, True]

or ideally, with padding to always return 8 boolean values (i.e. one full byte):

[False, False, False, False, False, True, False, True]

Thanks

Was it helpful?

Solution

You can use numpy's unpackbits.

From the docs (http://docs.scipy.org/doc/numpy/reference/generated/numpy.unpackbits.html)

>>> a = np.array([[2], [7], [23]], dtype=np.uint8)
>>> a
array([[ 2],
       [ 7],
       [23]], dtype=uint8)
>>> b = np.unpackbits(a, axis=1)
>>> b
array([[0, 0, 0, 0, 0, 0, 1, 0],
       [0, 0, 0, 0, 0, 1, 1, 1],
       [0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8)

To get to a bool array:

In [49]: np.unpackbits(np.array([1],dtype="uint8")).astype("bool")
Out[49]: array([False, False, False, False, False, False, False,  True], dtype=bool)

OTHER TIPS

Not a built in method, but something to get you going (and fun to write)

>>> def int_to_binary_bool(num):
        return [bool(int(i)) for i in "{0:08b}".format(num)]

>>> int_to_binary_bool(5)
[False, False, False, False, False, True, False, True]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top