6

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?

5 Answers 5

15

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

Try that:

Bitmasks = []
Bitmasks.append(int("0001", 2))
Bitmasks.append(int("0010", 2))
Bitmasks.append(int("0100", 2))
Bitmasks.append(int("1000", 2))

myNumber = 12
Bools = []
for bm in Bitmasks:
    Bools.append(myNumber|bm==myNumber)

Comments

0
R = 16
list = []
print bin(R)[2:]
for i in bin(R)[2:]:
    if (i=="1"):
        list.append(True)
    else:    
        list.append(False)


print list

output-click here

[True, False, False, False, False]

Comments

-2
x = 7
strBin = str(bin(x))
lsBoolVal = [i == '1' for i in strBin[2:].zfill(4)]

4 Comments

Yes I have checked it.
You should still check it; it doesn't work very well, even with the example you provide here; you have to return 4 bits and with x=7 you only return three bits here.
This time it seems to work! But why do you say "no"? You tried several times and at each time I noticed some mistakes in your code; the very first version wasn't even working because of a syntax error (which is why I asked if you had tried your code which couldn't obviously be the case); the second time I told you your function was returning three bits when running the very exact piece of code you were providing because it was actually the case. Why are you saying "no" after having fixed it? I am happy that you could fix it; we are here for helping each other. Regards.
I am saying no for error not present now. But I think you must now flag my answer to get deleted, as it'll misguide others that my current answer is wrong, which is not the case now or you must revert your downvote.

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.