1
\$\begingroup\$

I've been searching for methods to convert a bitarray into integer. Now I'm using this code:

def bin2int(bin_array):
    int_ = 0
    for bit in bin_array:
        int_ = (int_ << 1) | bit
    return int_

where bin_array is a bitarray randomly filled. I'm curios about other methods that you know of, like functions from bitarray or numpy...

\$\endgroup\$
4
  • 2
    \$\begingroup\$ Just out of interest: how do you know that this is the quickest way? \$\endgroup\$ Commented Jan 15, 2021 at 16:36
  • \$\begingroup\$ I don't, that's the point \$\endgroup\$ Commented Jan 16, 2021 at 20:43
  • \$\begingroup\$ Ah, in that case the title shouldn't make that claim. I've edited. \$\endgroup\$ Commented Jan 16, 2021 at 23:05
  • \$\begingroup\$ Here's a numpy version stackoverflow.com/questions/49791312/… \$\endgroup\$ Commented Jan 17, 2021 at 2:11

1 Answer 1

1
\$\begingroup\$

There is a method in bitarray.util called ba2int:

from bitarray import bitarray
from bitarray.util import ba2int

ba = bitarray('1001')  # 9

i = ba2int(ba)

print(f'Value: {i} type: {type(i)}')
# Output: Value: 9 type: <class 'int'>

From the doc:

ba2int(bitarray, /, signed=False) -> int

Convert the given bitarray into an integer. The bit-endianness of the bitarray is respected. signed indicates whether two's complement is used to represent the integer.

\$\endgroup\$

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.