What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Convert Binary String to Int in Python (with code)

  • Sep 12, 2023
  • 4 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Riddhima Agarwal
Convert Binary String to Int in Python (with code)

Computers have a different language and they cannot understand words and sentiments as we all do. The only thing a machine or a computer can understand is two signals: 0 and 1 respectively. The language comprising these sequences is known as binary language. In this tutorial, we will discuss how we can convert a Binary String into an Integer in Python.

But before we divide deep into different conversion methods, let us have a quick recap of strings and integers.

What are Strings?

Strings in Python are defined as arrays of bytes representing Unicode characters. If you come with experience in other programming languages, then you may understand strings as an array of characters. However, this is not exactly true in Python, because it has no char or character data type. A single character is just a string with a length of 1 for Python. 

What are Integers?

Integers or int is just another data type in Python that is used to store whole numbers. This data type, however, cannot accommodate decimals or fractions. Let us now look at the ways in which we can accomplish the required conversion.

Convert a Binary String to an Integer in Python

Characters and numbers are encoded in the memory as binary numbers. So, if we have a string containing a binary number, we should be able to convert it to its corresponding number. This is what we will achieve in this section.  There are two ways in which we can do the conversion, let's go through both of them one by one.

1) Using bitstring module

Python is known for its wide array of modules and its large open-source community. Out of this huge collection of open-source libraries, the module that we will be using here is the bitstring module. This module makes the creation, manipulation, and analysis of binary data as simple as possible.

The class that we will be using to achieve our task is the BitArray class. This class is present inside the bitstring module and has a property called int. This property contains the signed two’s complement integer representation of the bitstring.

Before we can access this property, we are required to create an object of the BitArray class. The constructor of this class requires us to specify an initializer, which tells the class about the type of data we will be providing it with.

In this can since we are dealing with binary string, the initializer that we will be using is bin. After initializing our object we will access the int property of the object to get the required integer. For example:

from bitstring import BitArray

# initialize a binary string
bString = "10101"

# conversion
value = BitArray(bin=bString).int

# display the converted value
print(value)

 

Output:

21

 

Please note that you will have to install the bitstring module into your system using the pip command.

2) Using int

This approach is a fairly simple one and doesn’t require any installation of packages.

The built-in function called 'int' in Python can be used to convert binary string to integer. This function takes the string which we want to convert as its first argument and the base of the number as its second argument. Since here we are dealing with a binary number the base is 2. This method then returns the integer value of the binary string.

Let's take an example:

# initialize a binary string
bString = "10101"

# conversion
value = int(bString, 2)

# display the converted value
print(value)

 

Output:

21

 

How to Convert a String to Binary and back in Python?

In Python, we may use the bin() function to convert a string to binary. When given an integer as an input, the bin() method returns the integer's binary form. We may loop through the string and, using the ord() function, convert every character to its matching ASCII value to determine each character's binary value.

After that, we can use the bin() function to obtain the binary form of the ASCII value. The Python code to convert a string to binary is as follows:

def stringToBinary(string):
    binary = ''
    for char in string:
        binary += bin(ord(char))[2:].zfill(8) + ' '
    return binary[:-1]

 

In Python, we can use the chr() function to convert binary to string. The character that corresponds to an integer is returned by the method chr().

We can divide the binary string into groups of 8 bits, use the int() function alongside the base argument set to 2 (binary) to convert each group into the corresponding integer, and then pass an integer argument to the chr() function to obtain the corresponding character. The original string can then be obtained by joining all the characters.

The Python code to convert binary to string is as follows:

def binaryToString(binary):
    string = ''
    binaryList = binary.split(' ')
    for binaryValue in binaryList:
        string += chr(int(binaryValue, 2))
    return string

 

Conclusion

Python provides us with a large number of methods and libraries that make the task of conversion very easy and convenient. In this article, we learned about 2 different ways in which we can convert a binary string into an integer. If you have this question in your homework, reach us for expert-level Python assignment help online.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Riddhima Agarwal
Hey, I am Riddhima Agarwal, a B.tech computer science student and a part-time technical content writer. I have a passion for technology, but more importantly, I love learning. Looking forward to greater opportunities in life. Through my content, I want to enrich curious minds and help them through their coding journey