How To Convert Binary To Number In Python

Converting Binary to number is a fundamental operation that programmers need to perform frequently. Binary is a numbering system that uses only two digits, 0 and 1, to represent any number or character.

It is commonly used in computer programming and digital electronics, where these two values are represented by the presence or absence of an electrical charge.

In this blog, we will see some important concepts related to binary and number data types in Python. We will also look at some practical use cases for binary to number conversion in Python.

Why is converting binary to number in python needed?

There are the some reasons why converting binary to number in python  is needed:

  1. In computer systems, data is often represented in binary format. Converting binary to a number allows programmers to manipulate and store data in a more convenient and efficient way.
  1. Converting binary to number in Python is essential when dealing with binary data from external sources such as sensors, microcontrollers, or other hardware devices.
  1. Binary data is often used in cryptography and encoding schemes, and converting it to numbers in Python is necessary to perform operations such as encryption and decryption.

How To Convert Binary To Number In Python

Here are six different approaches to how to convert binary to number in python with detailed solution steps, code, and output for each approach:

  1. Using binary shift operator
  2. Using bitarray library
  3. Using math.pow() function
  4. Using Bitwise AND operator
  5. Using NumPy
  6. Using eval() function

Let’s dive in more with examples to each approach.

Approach 1: Using Binary Shift Operator

The Binary shift operator is a worldwide known operator in computer programming which facilitates the shifting of individual bits within a numerical value either towards the left or right, by a specified number of positions. .

Pros:

  1. Fastest approach for converting binary to a simple number.
  2. Simple and easy to understand code.
  3. Built-in Python operator.

Cons:

  1. Can only convert positive numbers.
  2. Limited to 32 bits.
  3. Requires knowledge of binary arithmetic.

Code:

def binary_to_number(binary):
    result = 0
    for digit in binary:
        result = result << 1
        if digit == '1':
            result += 1
    return result

binary_num = '111010'
int_num = binary_to_number(binary_num)
print(int_num)

Output:

58

Code Explanation

  1. The code defines a function binary_to_number that takes a binary string as input and returns its integer equivalent using a loop and bit-shifting operations.
  2. The function initializes a variable result to 0 and iterates through each digit in the binary string.
  3. For each digit, the function shifts the current result one bit to the left.
  4. Finally, the value is printed to the console after calling the function with a test input.

Approach 2: Using bit array library

The Python bitarray library is an incredibly useful tool that offers a highly efficient method of manipulating boolean arrays. With its impressive capabilities, one can effortlessly convert a binary to bitarray and then convert the bitarray to number.

Pros:

  1. Efficient handling of large binary numbers.
  2. Can handle negative binary numbers.
  3. Supports a wide range of operations on bit arrays.

Cons:

  1. Requires installation of an external library.
  2. May not be the most efficient approach for small binary numbers.
  3. Has a learning curve to understand the library’s syntax.

Code:

def binary_to_number(binary):
    bits = binary[::-1]
    result = 0
    for i, bit in enumerate(bits):
        result += int(bit) * 2**i
    return result

binary_num = '111110'
int_num = binary_to_number(binary_num)
print(int_num)

Output:

62

Code Explanation:

  1. Define a function called “binary_to_number” that takes in a string parameter “binary”.
  2. Reverse the order of the characters in the “binary” string and store it in a new variable called “bits”.
  3. Use a loop to iterate over each character in “bits” and convert it to an integer.
  4. Return the final value of “result” as the decimal equivalent of the original binary string.

Approach 3: Using math.pow() function

The math.pow() function is an inbuilt function endowed with the great ability to elevate a given number to a user-specified power.

Pros:

  1. Can handle large binary numbers.
  2. Easy to understand code.
  3. Built-in Python function.

Cons:

  1. Can only convert positive binary numbers.
  2. Not the most efficient approach for small binary numbers.

Code:

import math

def binary_to_number(binary):
    simple = 0
    for i, bit in enumerate(binary[::-1]):
        if bit == '1':
            simple += math.pow(2, i)
    return simple

binary_num = '11110'
int_num = binary_to_number(binary_num)
print(int_num) 

Output:

30.0

Code Explanation:

  1. Define a function binary_to_simple that takes a binary string as input..
  2. Iterate over each bit in the binary string in reverse order.
  3. If the current bit is a 1, add 2 raised to the power of its position to the simple variable using the math.pow() function.
  4. Return the simple variable.

Approach 4: Using Bitwise AND operator

The bitwise AND operator is a logical AND operation that can be performed on each bit of two binary numbers with ease. This approach is widely used in the field of computing to convert binary to a number.

Pros:

  1. Can handle large binary numbers.
  2. Efficient for small binary numbers.
  3. Built-in Python operator.

Cons:

  1. Can only convert positive binary numbers.
  2. May be less efficient than other approaches for large binary numbers.

Code:

def binary_to_number(binary):
    simple = 0
    for i, bit in enumerate(binary[::-1]):
        if bit == '1':
            simple += 1 << i
    return simple

binary_num = '10010'
int_num = binary_to_number(binary_num)
print(int_num) 

Output:

18

Code Explanation:

  1. Define a function binary_to_simple that takes a binary string as input.
  2. Iterate over each bit in the binary string in reverse order.
  3. If the current bit is a 1, add the result of shifting 1 to the left by its position to the simple variable.
  4. Return the simple variable.

Approach 5: Using NumPy

NumPy is a powerful library for scientific computing in Python. It provides efficient array operations and mathematical functions to convert binary to number.

Pros:

  1. Efficient handling of large binary numbers.
  2. Supports a wide range of operations on arrays.
  3. Can handle both positive and negative binary numbers.

Cons:

  1. Requires installation of an external library.
  2. May not be the most efficient approach for small binary numbers.
  3. Has a learning curve to understand the library’s syntax.

Code:

import numpy as np

def binary_to_number(binary_num):
    int_num = int(binary_num, 2)
    return int_num

binary_num = '110010'
int_num = binary_to_number(binary_num)
print(int_num)

Output:

50

Code Explanation:

  1. The numpy library is imported into the script.
  2. A function named binary_to_number is defined.
  3. The binary string ‘110010’ is assigned to the variable binary_num.
  4. Finally, the value of int_num is printed to the console.

Approach 6: Using eval() function

The eval() function plays a crucial role in interpreting a given string argument as a Python expression. With its incredible flexibility and versatility, eval() has become an essential tool for programmers who need to convert binary data to numeric values.

Pros:

  1. Short and simple code.
  2. Can handle both positive and negative binary numbers.
  3. Built-in Python function.

Cons:

  1. May not be the most efficient approach for large binary numbers.
  2. Eval() can execute arbitrary code, which can be a security concern if used with untrusted input.
  3. Limited error handling and may raise exceptions if the input is not a valid binary string.

Code:

def binary_to_number(binary):
    return eval('0b' + binary)

binary_num = '11101'
int_num = binary_to_number(binary_num)
print(int_num)

Output:

29

 Code explanation:

  1. Define a function called binary_to_number that takes a binary string as input.
  2. Use the built-in eval() function to convert the binary to number.
  3. Store the converted integer in a variable called int_num.
  4. Print the result to the console.

Best Approach To Convert Binary To Number In Python

The best qualities of Using Binary Shift Operator approach are:

  1. This approach is one of the fastest and most efficient ways to convert binary to a simple number as it uses bitwise operations which are optimized for speed.
  2.  The binary shift operator is a built-in Python operator which means that it is widely available and well-supported.
  3. The binary shift operator is a built-in operator in Python, making this approach simple to implement.
  4. It is a very fast approach for converting binary to a simple number because it only requires bit shifting and addition operations.

Sample Problems on Converting Binary To Number In Python

Sample Problem 1:

Scenario: A perfume manufacturer wants to store the concentration of different fragrances in binary format to save memory. They need to convert the binary data to numbers to perform calculations on it..

Solution Steps:

  1. The code defines a variable binary_concentration that stores a binary number as a string.
  2. It then creates an integer variable int_concentration with an initial value of 0.
  3. The for loop iterates over each bit in the binary number and updates the integer variable int_concentration by left-shifting it by 1 bit.
  4. Finally, the code prints the integer value of the binary number.

Code:

# Binary data
binary_concentration = '1110101'

# Convert to number using binary shift operator
int_concentration = 0
for bit in binary_concentration:
    int_concentration = (int_concentration << 1) | int(bit)
print(int_concentration)

Output:

117

Sample Problem 2:

Scenario: An Aeroplane manufacturer needs to store the binary data for the on/off status of various components in the cockpit. They need to convert the binary data to numbers to analyze the performance of different components.

Solution Steps:

  1. A variable called ‘binary_status’ is defined and assigned a string value which represents a sequence of binary digits.
  2. The ‘int()’ function is used to convert the binary string to an integer value.
  3. The resulting integer value is assigned to a new variable called ‘int_status’.
  4. The integer value is printed to the console using the ‘print()’ function.

Code:

# Binary data
binary_status = '1011011'

# Convert binary to number using bit array library
int_status = int(binary_status, 2)

print(int_status)

Output:

91

Sample Problem 3:

Scenario: Suppose you are working on an Instagram analytics project where you need to analyze the engagement of your followers. You have access to the number of likes and comments on each post, but the data is in binary format so you need to convert to numbers for performing statistical analysis.

Solution Steps:

  1. The code imports the math module, which provides mathematical functions and constants in Python.
  2. The code defines two variables like and comments that store binary data as strings.
  3. The code converts the binary data to integer values using the sum() and math.pow() functions.
  4. The code then prints the integer values of likes_int and comments_int to the console.

Code:

import math

# binary data
likes = '101101'
comments = '110011'

# convert binary to number using math.pow() function
likes_int = sum(int(likes[i]) * math.pow(2, len(likes)-1-i) for i in range(len(likes)))
comments_int = sum(int(comments[i]) * math.pow(2, len(comments)-1-i) for i in range(len(comments)))

# print integer values
print(likes_int)
print(comments_int)

Output:

45.0
51.0

Sample Problem 4:

Scenario: You are a computer scientist working for a film production company that is creating a new movie series. You have been given the task of converting binary to numbers to help with the creation of special effects for the movie.

Solution Steps:

  1. A binary number is represented as a string in the variable binary_num.
  2. The built-in int() function is used to convert the binary string into its integer.
  3. The resulting integer value is stored in the variable int_num.
  4. The print() function is used to output the value of int_num.

Code:

# Binary number as a string
binary_num = "101010"

# Convert binary to number using bitwise AND operator
int_num = int(binary_num, 2)

# Print the integer value
print(int_num)

Output:

42

Sample Problem 5:

Scenario: A television manufacturer stores the binary data for various channels, program timings, and settings. They need to convert the binary data to numbers to perform different operations such as changing channels or adjusting volume.

Solution Steps:

  1. Start with a binary number represented as a string.
  2. Import NumPy library for array manipulation.
  3. Convert the binary string into an array of integers using NumPy and pack the bits into a byte.
  4. Convert the resulting array into an integer using the item() method and print the value.

Code:

# Binary number as a string
binary_channel = "1011101"

# Convert binary to number using NumPy 
import numpy as np
int_channel = np.packbits(np.array([int(bit) for bit in binary_channel], dtype=np.uint8)).item()

# Print the integer value
print(int_channel)

Output:

186

Sample Problem 6:

Scenario:  A developer needs to read binary data stored in a text file and convert it to numbers to perform various data processing tasks. They don’t want to write a separate conversion function for each data type, so they decide to use the eval() function to convert the binary data to numbers.

Solution Steps:

  1. Declare a string variable ‘binary_channel’ and assign it the value “1011101”, which represents a binary number.
  2. Convert the binary string to an integer using the eval() function .
  3. Store the converted integer in a new variable ‘int_channel’.
  4. Print the value of ‘int_channel’ to display the converted binary number as an integer.

Code:

# Binary number as a string
binary_channel = "1011101"

# Convert binary to number using eval() function
int_channel = eval('0b' + binary_channel)

# Print the integer value
print(int_channel)

Output:

93

Conclusion:

In this blog, we have explored the various ways of converting binary to number in Python but  using the binary shift operator comes up as the best approach. Using the binary shift operator in python is an efficient and simple approach for converting binary numbers to numbers,particularly when dealing with large sets of data. Overall, understanding how to convert binary to number is a useful skill for any Python programmer.