How to Convert a Binary String to an Integer in Python?

In Python, you can use the int() method (with a base 2 as the second argument) to convert a binary string to its integer equivalent, for example, like so:

num = int('11000000111001', 2)

print(num) #=> 12345

This also works with binary strings that have the "0b" (or "0B") binary radix prefix:

# Python 2.6+
num = int('0b11000000111001', 2)

print(num) #=> 12345
# Python 2.6+
num = int('0B11000000111001', 2)

print(num) #=> 12345

Specifying an invalid binary number would raise the following error:

// ValueError: invalid literal for int() with base 2: '0o11111'
int('0o11111', 2)

If the binary string has 0b (or 0B) radix prefix, then you may also specify 0 as the second argument (i.e. the base) to the int() method, which would make it infer the value:

# Python 2.6+
num = int('0b11000000111001', 0)

print(num) #=> 12345

This could be useful, for example, if a variable with a number can be of different types (such as binary, octal, hexadecimal, etc.).


Hope you found this post useful. It was published . Please show your love and support by sharing this post.