I have an integer of which I know that it's between 0 and 15, i.e., can be expressed in 4 bits. I would like to get the bit representation of that array as a Boolean array, i.e.,
0: [False, False, False, False],
1: [True, False, False, False],
2: [False, True, False, False],
# [...]
15: [True, True, True, True]
How can I best achieve that?
Through formatting as binary:
def int_to_bool_list(num):
bin_string = format(num, '04b')
return [x == '1' for x in bin_string[::-1]]
or bitwise and:
def int_to_bool_list(num):
return [bool(num & (1<<n)) for n in range(4)]
The first function requires that the bin_string
contents be reversed (with [::-1]
) because string formatting formats the number the way we read it - most significant bit first, whereas the question asked for the bits in least significant bit first order.
With list comprehension:
my_int = 3
[b == '1' for b in bin(my_int)[2:].rjust(4)[::-1]] # Convert, pad and reverse
output:
[True, True, False, False]
1 2 4 8 = 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With