Search code examples
pythonbit-manipulationbitwise-operatorsbitbitwise-and

How to convert a long binary string to an integer in python? (base > 36)


I have a bit string of length 128 and want to perform Bitwise AND on it. To do that, I want to first convert the bit string into a integer.

int("00000010000....0000000",128)

However, python gives an error:

ValueError: int() base must be >= 2 and <= 36

My question is how can I convert a long bit string into an integer in Python? Or is there any other way that I can do Bitwise AND without converting the bit string into an integer?


Solution

  • int() takes a literal and base. What you are looking to do is convert the literal that is in base 2. The literal can be of any length:

    int("00000010000....0000000", 2)
    

    The python documentation for int() can be found here: Python2 Python3