Reputation: 7674
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
Upvotes: 4
Views: 5091
Reputation: 20938
This will do what you want:
sum(v << i for i, v in enumerate(p[::-1]))
Upvotes: 11
Reputation: 1165
I came across this question because I wanted to do the same thing.
Mine was an X/Y problem, however: I was implementing a function and thought that I wanted to convert the input array of bits into an integer.
What I really wanted to do was to use an IntFlag
from the enum
built-in instead of my custom implementation.
Here's the standard example from the documentation:
>>> from enum import IntFlag
>>> class Perm(IntFlag):
... R = 4
... W = 2
... X = 1
...
>>> Perm.R | Perm.W
<Perm.R|W: 6>
>>> Perm.R + Perm.W
6
>>> RW = Perm.R | Perm.W
>>> Perm.R in RW
True
It also works the other way:
>>> Perm(7)
<Perm.R|W|X: 7>
My use case was for a bitmask:
class BitMask(IntFlag):
flag1 = 2**0
flag2 = 2**1
flag3 = 2**2
flag4 = 2**3
flag5 = 2**4
# etcetera
With an IntFlag I can get the integer value while still retaining the useful information of what each bit represents.
Upvotes: 0
Reputation: 107347
To convert integer strings in different bases, simply use the int()
function with an
appropriate base.
>>> int(''.join('1' if i else '0' for i in p), 2)
233
Using generators ([1 if i else 0 for i in p]
) have a more performance than map
(map(int, p)
)here !
Upvotes: 2
Reputation: 19753
>>> p = [True, True, True, False, True, False, False, True]
>>> int("".join(map(lambda x: x and '1' or '0',p)),2)
233
int with base 2 give integer from binary
Upvotes: 0
Reputation: 17730
Just use algebra:
sum(2**i for i, v in enumerate(reversed(p)) if v)
Upvotes: 7