Javascript required
Skip to content Skip to sidebar Skip to footer

How to Make a Number an Integer in Python

In this Python tutorial, we will learn various ways to convert a binary number into a decimal number in Python. We will discuss some in-built methods as well as create our own methods for converting a binary string into a decimal.

  • How to convert binary string to decimal in Python
  • Python program to convert binary to integer
  • Python convert binary to float
  • Python program to convert binary to octal
  • Binary to decimal in Python without inbuilt function
  • Binary string to decimal in Python without inbuilt function
  • Python program to convert binary to decimal using while loop
  • Python program to convert binary to decimal using recursion
  • Python program to convert binary to hexadecimal
  • Python program to convert binary to hexadecimal using while loop
  • Python program to convert binary to ASCII
  • Convert binary list to decimal Python
  • Python program to convert decimal to binary and vice versa
  • Python program to convert binary to decimal octal and hexadecimal

How to convert binary string to decimal in Python

Let us understand the logic behind this conversion with the help of an example.

Consider the binary number: 1011

Now we will multiply every single digit with the multiples of 2 starting from the unit's place. Then we will add all the resulting values. The calculation will be like this:

Decimal number= 1 * 23 + 0 * 22 + 1 * 21 + 1 * 20,

which is equivalent to 8 + 0 + 2 + 1 = 11

You can convert a binary string into a decimal in Python in various ways. You can use either the int() or the float() functions to convert a binary string into an integer or a float number respectively.

Another way is to use our own logic to create a Python program. We will use the logic that we saw in the above explanation.

Read Python Check if a variable is a number

Python program to convert binary to integer

First of all, let us convert a binary string into an integer using the int() function in Python. the following is a simple Python program to convert a binary string into an integer:

          number= input('Enter a Binary number:') dec_number= int(number, 2) print('The decimal conversion is:', dec_number) print(type(dec_number))        
  • In the above program, we are taking a string input. This string number is supposed to be a binary number.
  • Secondly, we are using the int() function and passing the binary string to this function.
  • The second argument i.e 2 is representing that we are converting a binary number. Let us see the output now.
Python convert binary to int
Binary to int conversion
  • You can see that the number is converted into a decimal and the data type is int i.e an integer.

In this way, you can convert a binary string into an integer using an in-built function.

Read Check if NumPy Array is Empty in Python

Python convert binary to float

Let us see a Python program to convert a binary string into a float number. We will use the float() method in this example.

          number= input('Enter a Binary number:') int_number= int(number, 2) float_number= float(int_number) print('The float conversion is:', float_number) print(type(float_number))        
  • You cannot use the float() function to directy convert a binary string into a float value. We can use the int() function to convert a binary string into an integer and then use the float() function to chnage the data type into float.
Python convert binary to float
Binary to float conversion

Read Python remove substring from a String + Examples

Python program to convert binary to octal

There are multiple ways to convert a binary number into an octal. I will demonstrate various examples of this type of conversion.

Example 1: Taking binary string input and use the in-built functions for conversion

          binary_num= input('Enter a binary to convert into octal:') decimal_num= int(binary_num, 2) octal_num = oct(decimal_num) print('Octal number representation is:', octal_num)        
Python program to convert binary to octal
Binary to octal conversion using the in-built functions

This is the simplest method for converting a binary string into an octal number. Let us see another example.

Example 2: Taking a binary number and using our own logic for conversion.

In Python, If you want to convert a binary number into an octal, you have to convert the binary into a decimal first, and then convert this decimal number into an octal number.

          # Taking user input binary_num = input("Enter the Binary Number: ") dec_num = 0 oct_num=0 m = 1  # Converting binary into decimal for digit in binary_num:     digit= int(digit)     dec_num = dec_num + (digit * m)     m = m * 2  # Converting decimal into octal m = 1  while (dec_num != 0):     oct_num += (dec_num % 8) * m;     dec_num = int(dec_num/8)     m *= 10;  print("Equivalent Octal Value = ", oct_num)        
  • In the above program, we have used the for loop to convert a binary into decimal.
  • Then we used the while loop to convert that decimal into an octal.
  • To convert a number from decimal to octal, we keep on dividing a number by 8 and collect all the reaminders after every division until the number becomes zero.
  • Then, these remainders are placed at their respective postitions i.e. starting from unit's place.
  • Let us seee an example. Consider the binary number 11111 which is quivalent to 31 in decimal.
    • 31 can be written as 31 = 8 * 3 + 7. the remainder i.e. 7 will be the digit at the one's place of the octal number.
    • The quotient i.e. 3 is our new number and can be writtens as : 3 = 8 * 0 +3, leaving 3 as remainder. This remainder i.e. 3 will be the ten's digit.
  • The quotient has become 0. Therefore, we will stop here and the resultant octal number will be 37.

Thus, you might have learned how you can convert a binary to an octal using various methods in Python.

Read Python 3 string replace() method

Binary to decimal in Python without inbuilt function

In this section, you will learn how to convert a binary string into a decimal without using any in-built function in Python. We will implement our own logic to perform this task. Look at the following Python program.

          binary_num = int(input("Enter the Binary Number: ")) dec_num = 0 m = 1 length = len(str(binary_num))  for k in range(length):     reminder = binary_num % 10     dec_num = dec_num + (reminder * m)     m = m * 2     binary_num = int(binary_num/10)  print("Equivalent Decimal Value = ", dec_num)        

Let me explain some parts of the program.

  • dec_num is the decimal number that we will get as a result. Initially, it's value is zero.
  • The m variable inside the loop is the value of exponential term of 2 after every loop.
  • We are multiplying every digit of the binary number to the value of m.
  • Finally, adding all the values after multiplication with the susequent powers of 2, we will get our final result.
Binary to decimal in Python without inbuilt function
Binary number to decimal conversion

Thus, you might have learned how to convert a binary number into a decimal number without using any inbuilt function in Python.

There are some other alternative methods also. You will find them in the upcoming sections.

Also, check Python 3 string methods with examples

Binary string to decimal in Python without inbuilt function

In the above section, we converted a binary number data type into a decimal in Python. This time, we will convert a binary string into a decimal i.e. the input will be a string.

          binary_num = input("Enter the Binary Number: ") dec_num = 0 m = 1  for digit in binary_num:     digit= int(digit)     dec_num = dec_num + (digit * m)     m = m * 2  print("Equivalent Decimal Value = ", dec_num)        
  • In the above program, we are taking the binary string input and iterating over it using the for loop.
  • Inside the loop, we are converting every binary character into integer data type.
  • After that we are multiplying the binary digit with the subsequent terms of 2's exponent values.
  • At the end we are adding the reslting values and storing inside a variable.
Binary string to decimal in Python without inbuilt function
Binary string to decimal conversion

Thus, you might have learned how to convert a binary string into a decimal without using any in-built functions in Python.

Read Python compare strings

Python program to convert binary to decimal using while loop

In this section, you will see a Python program to convert a binary number into a decimal number using the while loop. The Python program is written below:

          def BinaryToDecimal(num):     expo =1     dec_num= 0     while(num):         digit = num % 10         num = int(num / 10)                  dec_num += digit * expo         expo = expo * 2     return dec_num  # Taking user input num = int(input('Enter a binary number: '))  # Displaying Output print('The decimal value is =', BinaryToDecimal(num))        
  • In the above Python program, we have created a function that will convert a binary number into a decimal number using a while loop.
  • Then, we are taking the user input and pasing this input to the function while displaying result through the print statement.
  • Let us give a sample input and check our program.
Python program to convert binary to decimal using while loop
Binary to decimal conversion using the while loop

Hence, in this way, you can use the while loop in Python to convert a binary number to decimal.

Read Python find substring in string

Python program to convert binary to decimal using recursion

You can also use the recursion technique to convert a binary number into a decimal in Python. I will demonstrate this with an example.

Recursion is a technique in which a function calls itself inside its body for a particular condition. If the condition is satisfied it will call itself. Otherwise, the program will terminate.

The following is a Python program to convert a binary number into a decimal using the recursion method:

          # Defining the function def BinaryToDecimal(num, expo=1):     if num== 0:         return 0     else:         digit= num % 10         num= int(num / 10)         digit= digit * expo         return digit + BinaryToDecimal(num, expo * 2)          # Taking user input num = int(input('Enter a binary number: '))  # Displaying Output print('The decimal value is =', BinaryToDecimal(num))        
  • In the above program, we have defined a function that takes two arguments i.e a binary number and the exponential value of 2.
  • Initially, the exponential value will be 1 (i.e. 20).
  • We have specified a condition that the function will not call itself again if it has become zero.
  • Then, we will separate the last digit of the binary number, mulitply it with the current exponential term of 2 and return its sum with the recursively called function.
  • This time, we will pass the binary number without the last digit with the next exponenetial term of 2 to the called function.
Python program to convert binary to decimal using recursion
Binary to decimal conversion using recursion

In simple words, every time this function will return a decimal digit, and at the end of all executions, these decimal digits will be added and we will get the calculated decimal number.

Also read, Could not convert string to float Python

Python program to convert binary to hexadecimal

In this section, you will learn to convert a binary number into a hexadecimal number in Python.

Firstly, you have to convert the binary number into a decimal number. Then you can convert this decimal number into a hexadecimal number.

You can use the in-built functions to simply convert a binary number into a hexadecimal number. Below is the Python code snippet that you can use.

          # Taking binary input from user binary_num = input('Enter a binary number: ')  # Converting the binary input into decimal dec_num = int(binary_num, 2)  # Converting the decimal number into hexadecimal hex_num= hex(dec_num) print('Hexadecimal representation of this binary number is :', hex_num)        
Python program to convert binary to hexadecimal
Binary to hexadecimal conversion

Hence, in this way you can convert a binary number into a decimal number in Python.

Read Slicing string in Python

Python program to convert binary to hexadecimal using while loop

In this example, I will use a user-defined function to convert a binary input to hexadecimal using a while loop in Python.

The approach is the same as we discussed above for the conversion of binary numbers into octal. Firstly, we will convert the binary number into decimal and then convert this decimal number into hexadecimal.

We will define a list of hexadecimal characters and map the remainders with this list after every iteration while converting from decimal to hexadecimal.

          def convertToHex(binary_num):     # Converting binary into decimal     dec_num = 0     m = 1     for digit in binary_num:         digit= int(digit)         dec_num = dec_num + (digit * m)         m = m * 2     # defining the list of hexadecimal characters     hex_table = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A' , 'B', 'C', 'D', 'E', 'F']      # converting decimal into hexadecimal     hexadecimal = ''     while(dec_num > 0):         remainder = dec_num % 16         hexadecimal = hex_table[remainder]+ hexadecimal         dec_num = dec_num//16          return hexadecimal  #Calling the function print('The hexadecimal representation of the bianry is: ', convertToHex('11100111101'))        
Python program to convert binary to hexadecimal using while loop
Binary to hexadecimal conversion

In this way, you can convert a binary number into hexadecimal using the while loop in Python.

Read Extract text from PDF Python

Python program to convert binary to ASCII

In this section, you will learn about various conversions related to binary and ASCII values in Python. I will explain some examples where you will learn various use cases of these types of conversions.

Suppose you have a binary of a string and you want to convert it to the ASCII values. Let us create a binary of a string first using a Python program.

          message = "hello world" binary_text= ' '.join(format(ord(x), 'b') for x in message) print(binary_text)        

The above code will create a binary string of our message with a space character between every binary string of a particular alphabetical character. The resultant binary string will be:

          1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100        

Now let us convert these binary strings to their corresponding ASCII values.

          binary_text = '1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100' binary_values = binary_text.split() list1 = [] for i in binary_values:     list1.append(int(i, 2)) print(list1)        
Python program to convert binary to ASCII
Binary to ASCII conversion

We are using the int() function to convert the binary values into their corresponding ASCII values.

Hence, in this way, you can convert a binary string into ASCII in Python.

Read PdfFileWriter Python Examples (20 examples)

Convert binary list to decimal Python

In this section. I will explain an example in which I will create a list of binary numbers and convert them into decimals in Python. Look at the code below:

          binary_list = ['1011', '10101', '1101', '11111', '11100011'] decimal_list= (int(element, 2) for element in binary_list) for element in decimal_list:     print(element)        
Convert binary list to decimal Python
Conversion of a binary list into decimal

Also, if you have a list containing binary decimals with the integer data type, you have to convert the elements into string data types. For example:

          binary_list = [1011, 110110, 110111111, 1100011, 1010101] decimal_list= (int(str(element), 2) for element in binary_list) for element in decimal_list:     print(element)        

In the above example, you can see that the elements in the list are of integer data type. Therefore, we had to convert them into a string before converting them into decimal.

convert binary array to decimal python
Conversion of a binary list into decimal

Thus, you might have learned how you can convert a binary list into decimals in Python.

Read Convert string to float in Python

Python program to convert decimal to binary and vice versa

Let us now create a Python program that will convert a decimal number into a binary number as well as convert the binary number to a decimal number.

I will be using the in-built functions for conversions. The int() function can be used to convert a binary string into a decimal while the bin() function can be used to convert the decimal number into binary.

          def binToDeci():     binary_num = input('Enter a binary string:')     dec_num = int(binary_num, 2)     return dec_num  def deciToBin():     dec_num = int(input('Enter a decimal number:'))     binary_num= bin(dec_num).replace('0b', '')     return binary_num  print('''Enter 1 for Binary to decimal conversion Enter 2 for Decimal to Binary conversion ''') choice = int(input('Enter your choice: '))  if choice == 1:     print('Decimal conversion of the binary number is:', binToDeci()) elif choice == 2:     print('Binary represntation of the decimal number is:', deciToBin()) else:     print('Invalid Choice')        
Python program to convert decimal to binary and vice versa
Output in call test cases

Using this Python program, you can convert any decimal number into a binary number and vice-versa.

Read Convert float to int Python + Examples

Python program to convert binary to decimal octal and hexadecimal

In this section, you will see a Python program, that will take a binary number as the user input and return the equivalent decimal, octal and hexadecimal number.

          def binToDeci(binary_num):     dec_num = int(binary_num, 2)     return dec_num  def binToOct(binary_num):     dec_num = int(binary_num, 2)     oct_num= oct(dec_num)     return oct_num  def binToHex(binary_num):     dec_num = int(binary_num, 2)     hex_num= hex(dec_num)     return hex_num  binary_num = input('Enter a binary string:') print('Decimal representation of the binary number is:', binToDeci(binary_num)) print('Octal representation of the binary number is:', binToOct(binary_num)) print('Hexadecimal representation of the binary number is:', binToHex(binary_num))                  
Python program to convert binary to decimal octal and hexadecimal
Converting binary to various number systems

The 0o before the number represents that the number is octal and the 0x represents that the number is hexadecimal. if you do not want them with your output, you can use the replace() function as follows:

          def binToDeci(binary_num):     dec_num = int(binary_num, 2)     return dec_num  def binToOct(binary_num):     dec_num = int(binary_num, 2)     oct_num= oct(dec_num).replace('0o', '')     return oct_num  def binToHex(binary_num):     dec_num = int(binary_num, 2)     hex_num= hex(dec_num).replace('0x', '')     return hex_num  binary_num = input('Enter a binary string:') print('Decimal representation of the binary number is:', binToDeci(binary_num)) print('Octal representation of the binary number is:', binToOct(binary_num)) print('Hexadecimal representation of the binary number is:', binToHex(binary_num))                  
Python program to convert binary to decimal octal and hexadecimal
Output using the replace() function

You may like the following Python tutorials:

  • Python Count Words in File
  • Case statement in Python
  • Reverse a list in python
  • Get First Key in dictionary Python
  • Python dictionary increment value
  • Python Tkinter Spinbox

In this way, you can create a Python program that converts a binary number into decimal, octal, and hexadecimal numbers.

  • How to convert binary string to decimal in Python
  • Python program to convert binary to integer
  • Python convert binary to float
  • Python program to convert binary to octal
  • Binary to decimal in Python without inbuilt function
  • Binary string to decimal in Python without inbuilt function
  • Python program to convert binary to decimal using while loop
  • Python program to convert binary to decimal using recursion
  • Python program to convert binary to hexadecimal
  • Python program to convert binary to hexadecimal using while loop
  • Python program to convert binary to ASCII
  • Convert binary list to decimal Python
  • Python program to convert decimal to binary and vice versa
  • Python program to convert binary to decimal octal and hexadecimal

How to Make a Number an Integer in Python

Source: https://pythonguides.com/python-convert-binary-to-decimal/