Home > Backend Development > Python Tutorial > How Do I Convert Binary Strings to Integers in Python?

How Do I Convert Binary Strings to Integers in Python?

Mary-Kate Olsen
Release: 2024-12-12 17:05:12
Original
149 people have browsed it

How Do I Convert Binary Strings to Integers in Python?

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)
Copy after login

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}")
Copy after login

Output:

Binary: 100110 - Decimal: 38
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template