Converting Binary Strings to Integers in Python
Converting a base-2 binary number string to an integer involves transforming a sequence of binary digits (0s and 1s) into a numerical value. Python provides a straightforward way to perform this conversion using the built-in int() function.
Using the int() Function
The int() function can convert a string representation of a number into its integer equivalent. To specify the base of the number, you can pass an optional second argument, which defaults to 10 for decimal. For binary numbers, you would use a base of 2:
binary_string = '11111111' decimal_integer = int(binary_string, 2)
In this example, the binary string '11111111' is converted to a decimal integer with a value of 255.
Example Usage
Consider the following Python code:
def fromBinaryToInt(binary_string): """Converts a binary number string to an integer.""" return int(binary_string, 2) binary_number = '100110' integer_value = fromBinaryToInt(binary_number) print(f"Binary: {binary_number} - Decimal: {integer_value}")
Output:
Binary: 100110 - Decimal: 38
Documentation
You can find more information on the int() function in the official documentation for Python 2 or Python 3.
The above is the detailed content of How Do I Convert Binary Strings to Integers in Python?. For more information, please follow other related articles on the PHP Chinese website!