PlesleronTepryos
PlesleronTepryos

Reputation: 45

How to convert a list of boolean to a single int where each boolean is interpreted as a bit?

I have a list of bools and I want to convert it to a single int. For example: [True, True, False, True, False] -> 010112 -> 1110

I found this question: How do I convert a boolean list to int? but it's in C# and that doesn't help me.

My first try was to do

def bools2int(bools):
    n = 0
    for b in bools[::-1]:
        n *= 2
        n += b
    return n

which works.

But is there a more pythonic way to do this? And can it be done in one line?

Upvotes: 3

Views: 1765

Answers (2)

PlesleronTepryos
PlesleronTepryos

Reputation: 45

After some messing around, I found this

sum([b << i for i, b in enumerate(bools)])

which I think is a very pythonic solution.

Upvotes: 1

Chris
Chris

Reputation: 29742

IIUC, using built-in int(x, base=2):

l = [True, True, False, True, False]

def bool2int(bools):
    return int(''.join(str(int(i)) for i in reversed(bools)), 2)
bool2int(l)

Output:

11

Upvotes: 6

Related Questions