Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 4-bit integer into Boolean list

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?

like image 903
Nico Schlömer Avatar asked Nov 09 '15 11:11

Nico Schlömer


2 Answers

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.

like image 123
jepio Avatar answered Sep 30 '22 18:09

jepio


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
like image 37
Jerther Avatar answered Sep 30 '22 18:09

Jerther