Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bool array to integer

Is there any build in function in python to convert a bool array (which represents bits in a byte) like so:

p = [True, True, True, False, True, False, False, True]

into a byte array like this:

bp = byteArray([233])

I am aware oh numpy but I was looking for something within python itself

like image 297
Krimson Avatar asked Dec 04 '22 04:12

Krimson


2 Answers

This will do what you want:

sum(v<<i for i, v in enumerate(p[::-1]))
like image 140
simonzack Avatar answered Dec 06 '22 18:12

simonzack


Just use algebra:

sum(2**i for i, v in enumerate(reversed(p)) if v)
like image 22
Ruggero Turra Avatar answered Dec 06 '22 17:12

Ruggero Turra