What's the easiest way to produce a numpy Boolean array representation of an integer? For example, map 6 to np.array([False, True, True], dtype=np.bool).
4 Answers
If n is the integer, the expression (n & (1 << np.arange(int(floor(log(n, 2) + 1))))) > 0 will create a boolean array representing the bits, with the least significant bit in the first position.
For example,
In [224]: n = 5
In [225]: from math import floor, log
In [226]: n = 5
In [227]: (n & (1 << np.arange(int(floor(log(n, 2) + 1))))) > 0
Out[227]: array([ True, False, True], dtype=bool)
In [228]: n = 8
In [229]: (n & (1 << np.arange(int(floor(log(n, 2) + 1))))) > 0
Out[229]: array([False, False, False, True], dtype=bool)
In [230]: n = 514
In [231]: (n & (1 << np.arange(int(floor(log(n, 2) + 1))))) > 0
Out[231]: array([False, True, False, False, False, False, False, False, False, True], dtype=bool)
1 Comment
m = int(floor(log(n, 2) + 1)), so this solution is the shortest for me.First, use np.binary_repr to get the binary representation of the integer value. Remember to specify the bit-width you desire for your bit array here. I have included a way to programmatically determine the number of bits required to represent the given integer:
>>> n = 5
>>> bin_n = bin(n)
'0b101'
>>> smallest_length = n.bit_length()
3
>>> bin_array = np.binary_repr(5, width=smallest_length)
bin_array = '101'
Then, reverse the order of the bits in the output binary string:
>> reversed_bin_array[::-1]
reversed_bin_array = '101'
Then, finally to get an array of bits with the earlier-specified bit-width, use bitarray. I have found that the bitarray object is a very useful means to conveniently store and operate on bit arrays:
>>> bitarray('11110010') # from a string
I hope this helps, happy coding!
4 Comments
np.invert does not reverse the order of the bits.Here's an approach using np.binary_repr and np.fromstring -
np.fromstring(np.binary_repr(num), dtype=np.uint8)==49
Sample run -
In [39]: num
Out[39]: 17
In [40]: np.fromstring(np.binary_repr(num), dtype=np.uint8)==49
Out[40]: array([ True, False, False, False, True], dtype=bool)
np.int8, which is ugly, and the output puts most significant bits first, and groups the bits into groups of 8 — neither are things I want.