4

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

1
  • @vaultah the boolArray corresponds to 11101001 in binary which is 233 in dec Commented Nov 27, 2014 at 7:52

6 Answers 6

11

This will do what you want:

sum(v << i for i, v in enumerate(p[::-1]))
Sign up to request clarification or add additional context in comments.

1 Comment

reversed should be better then slicing [::-1] since you don't need a copy in this case.
7

Just use algebra:

sum(2**i for i, v in enumerate(reversed(p)) if v)

Comments

2

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 !

1 Comment

If you choose to use list comprehension or generator expression with conditional expression, why not use string literals: int(''.join('1' if i else '0' for i in p), 2)
1

Using int, you can convert binary representation to int object (by specifying base 2):

>>> p = [True, True, True, False, True, False, False, True]
>>> int(''.join(map(str, map(int, p))), 2)
233

Comments

0
>>> 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

Comments

0

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.

Comments

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.