简体   繁体   中英

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

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?

eg:

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 (ie one full byte):

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

Thanks

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)

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM