2

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

2 Answers 2

6

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.