Bin to decimal python

How to convert binary to decimal in Python

In this post, we are going to learn how to convert binary to decimal in Python with examples by using built-in functions and without built-in functions.

1. How to convert binary to decimal in python inbuilt function

In this example we are using Python built-in int() function returns an integer from a string or number. If no argument is passed then it returns 0 bypasses the base 2 to find decimal of binary number.

bin_to_dec*2 + int(num) 1*2+1 =1 1*2+1 = 3 2*3+1 = 7 2*7+1 =15

Python Program Example

binary = '1111' def BinaryToDecimal(binary): bin_to_dec = 0 for num in binary: bin_to_dec = bin_to_dec*2 + int(num) print("binary to decimal value is :", bin_to_dec) BinaryToDecimal(binary)
binary to decimal value is : 15

3. Binary to decimal in Python using function

In this example, we have defined a function BinaryToDecimal() and iterated over the binary digit in reversed order, and calculated decimal number by using the formula decimal_val += 2**count * int(num).

binary = '1111' def BinaryToDecimal(binary): decimal_val = 0 count = 0 for num in reversed(binary): decimal_val += 2**count * int(num) count+=1 print ('binary to decimal value is: ', decimal_val) BinaryToDecimal(binary)
binary to decimal value is : 15

4. Program to convert binary to decimal in Python

In this Python program, we are using the range loop to iterate over the binary number length

  • We have defined a function BinaryToDec().
  • We are using this formula to and calculate the decimal dec_val += int(binary[num]) * 2**abs((num – (len(binary) – 1)))

Python Program Example

binary = '1111' def BinaryToDec(binary): dec_val = 0 for num in range(len(binary)): dec_val += int(binary[num]) * 2**abs((num - (len(binary) - 1))) print('binary to decimal:',dec_val)

5. binary string to decimal in python

In this example, we have a binary number as a string and we have defined a function binaryToDec().

  • First, we have converted the binary number to list
  • Using for range loop to iterate over the list and claculating the decimal of binary number by mutiplying num to 2 power of number
  • The appending the result to result list and calulate the sum to get the decimal number.

Python Program Example

binary = '1111' def binaryToDec(bin_num): array = [int(num) for num in bin_num] array = array[::-1] reslst = [] for num in range(len(array)): reslst.append(array[num]*(2**num)) Dec_num = sum(reslst) print('binary to Decimal value is : ',Dec_num) binaryToDec(binary)
binary to Decimal value is : 15

6. While loop to convert binary to decimal

In this python program Example, we are using the while loop to convert binary numbers to decimals.

Читайте также:  Python if file has extension

Python Program Example

binary = int(input('Please enter binary number:')) def BinaryDecimal(bin_num): num,dec_num, base = bin_num, 0, 1 t_num = num while(t_num): digit = t_num % 10 t_num = int(t_num / 10) dec_num += digit * base base = base * 2 print('The binary to decimal value is =', dec_num) BinaryDecimal(binary)
The binary to decimal value is = 15

7. Binary to decimal in Python using recursion

In this example, we used recursion to define a function and call this function inside the same function to find the decimal of binary number.

Python Program Example

def binaryToDec(bin_num): if bin_num == 1 or bin_num == 0: return bin_num Strlen = len(str(bin_num)) digit = bin_num//pow(10,Strlen-1) return (pow(2,Strlen-1) * digit)+ binaryToDec(bin_num%pow(10,Strlen-1)) bin_num = int(input('Enter a Binary number: ')) decimal = binaryToDec(bin_num) print("binary to Decimal val is : ",decimal)
Enter a Binary number: 1111 binary to Decimal val is : 15

Summary

In this post, we have learned How to convert binary to decimal in Python using built-in function and without built-in function

Источник

Binary to decimal and vice-versa in python

Write Python code for converting a decimal number to it’s binary equivalent and vice-versa.

From decimal to binary Input : 8 Output : 1 0 0 0 From binary to decimal Input : 100 Output : 4

Decimal to binary

Keep calling conversion function with n/2 till n > 1, later perform n % 1 to get MSB of converted binary number. Example :- 7 1). 7/2 = Quotient = 3(greater than 1), Remainder = 1. 2). 3/2 = Quotient = 1(not greater than 1), Remainder = 1. 3). 1%2 = Remainder = 1. Therefore, answer is 111.

Python3

Time Complexity: O(log n)
Auxiliary Space: O(1)

Decimal to binary using bin():

Python3

Time Complexity: O(log n)
Auxiliary Space: O(1)
Binary to decimal

Example -: 1011 1). Take modulo of given binary number with 10. (1011 % 10 = 1) 2). Multiply rem with 2 raised to the power it's position from right end. (1 * 2^0) Note that we start counting position with 0. 3). Add result with previously generated result. decimal = decimal + (1 * 2^0) 4). Update binary number by dividing it by 10. (1011 / 10 = 101) 5). Keep repeating upper steps till binary > 0. Final Conversion -: (1 * 2^3) + (0 * 2^2) + (1 * 2^1) + (1 * 2^0) = 11

Python3

Time Complexity: O(log n)
Auxiliary Space: O(1)

Binary to decimal using int():

Python3

Time Complexity: O(1)
Auxiliary Space: O(1)

Method: Using format specifier

Python3

Built-in format function:

Another approach for converting decimal to binary is to use the built-in format function. This approach involves formatting a decimal number as a binary string using the b format specifier. To convert a binary string back to its decimal equivalent, you can use the built-in int function with the base parameter set to 2. For example:

Python3

Time complexity: O(1), or constant time. The code performs a fixed number of operations regardless of the size of the input. Specifically, the code:

  1. Reads an integer from the user and assigns it to n.
  2. Converts n to a string in binary format and assigns the result to binary.
  3. Converts binary to an integer and assigns the result to decimal.
  4. Prints binary and decimal.

The time complexity of the code is determined by the time it takes to read an integer from the user, which is a fixed operation. Therefore, the time complexity of the code is O(1).
Auxiliary Space: O(1), or constant space. The code uses a fixed number of variables, regardless of the size of the input. Specifically, the code uses:

  1. The variable n to store a single integer.
  2. The variable binary to store a string representation of n in binary format.
  3. The variable decimal to store the decimal equivalent of binary.
Читайте также:  Tqdm bar format python

Since the number of variables used is fixed and does not depend on the size of the input, the auxiliary Space of the code is O(1).

It’s worth noting that the specific time and space complexity of the conversion operations in this code may depend on the implementation of the built-in format and int functions. However, in general, these operations take O(1) time and space.

This article is contributed by Pushpanjali Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.

Источник

How to Convert a Number from Binary to Decimal in Python

Convert binary to decimal in Python

Would you like to learn how to convert a number from binary to decimal in Python? You are in the right place.

In Python, you represent binary numbers using 0b followed by the number. To convert a binary number to a decimal number Python provides the int() function. To convert the other way around, from decimal to binary, Python provides the bin() built-in function.

In this Python tutorial, we will cover a few examples to show you how to work with binary numbers in Python and how to convert numbers from the binary system to the decimal number system and vice-versa.

Let’s begin the conversion!

How to Convert Binary to Decimal Number in Python

As you know, the only two numbers you have in a binary number system are 0 and 1.

So, how can you convert a binary number into decimal using Python?

Let’s take, for example, the binary number 1010…

To specify a binary number in Python you have to use the prefix 0b. For example, you can write the binary number 1010 as 0b1010.

Let’s see what this looks like in the Python shell:

And here is something interesting…

This is what you get back if you print this number.

Even if we have specified a binary value, Python has stored this number as a decimal value.

To convert binary numbers to their decimal representation Python has a built-in function called int().

How to Convert Decimal to Binary in Python

So, if you have a decimal number, how can you print it in using its binary format?

To print a number in binary format Python provides the built-in function bin().

Let’s use the bin() function to print the previous number in binary format:

>>> number = 10 >>> bin(number) '0b1010'

To convert a decimal number into the corresponding binary number in Python you can use the bin() built-in function.

How to Calculate the Sum of Two Binary Numbers in Python

To calculate the sum of two binary numbers in Python we first specify the two numbers starting with 0b. Then we can use the + operator as usual to calculate the sum of the two numbers. Finally, we return the sum of the two numbers in binary format using the bin() built-in function.

>>> number1 = 0b1010 >>> number2 = 0b1010 >>> sum = number1 + number2 >>> sum 20 >>> bin(sum) '0b10100'

As explained previously, the sum is stored as a decimal number and to get it back as a binary number we use the bin() function.

Читайте также:  Failed to load external entity xml php

Let’s confirm that the result is correct:

The binary number 10100 is equal to 2 to the power of 2 plus 2 to the power of 4.

How to Convert a Binary String into a Decimal Number

Previously we have seen that when you specify a binary number Python automatically stores it as a decimal.

You might also find Python programs in which binary numbers are represented using a string like in the example below:

>>> number = "0b1010" >>> number '0b1010'

How do you convert a binary string into the decimal equivalent?

Let’s try to use the int() function:

>>> int(number) Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: '0b1010'

Hmmm…what’s causing this error?

Python is not able to understand the value “0b1010” because it assumes it’s a decimal number (see “base 10” in the error).

The int() function allows passing, as the second argument, the base of the number. In this case, the base is 2 considering that we are working with a binary number.

That’s better, we have converted a binary string into a decimal number.

Function to Convert Binary to Decimal Number

Now that we know the basic concepts of binary numbers in Python, it’s time to write a Python program to convert a number from binary to decimal.

Let’s create a Python function that takes a binary number as a string and returns its decimal value. We will use what you have learned in the previous section.

def convert_binary_to_decimal(bin_num): return int(bin_num, 2)

This function takes a binary number as input and returns its decimal value using the int() function.

Here is how you can call this function:

number = "0b1011" print(convert_binary_to_decimal(number)) [output] 11

You can improve this Python program using the input() function and give the result back to the user with the string format() method.

number = input("Please insert a binary number: ") print("The decimal value for binary number <> is <>".format(number, convert_binary_to_decimal(number)))

Execute the program and provide a binary input:

Please insert a binary number: 0b1100110 The decimal value for binary number 0b1100110 is 102

Conclusion

In this tutorial, we have seen how to work with binary numbers in Python and how to convert a binary number to decimal and a decimal number to the binary equivalent using Python built-in functions.

We have also created a custom function that performs this conversion in Python so we can include it in your Python code.

Now it’s your time to use what you have learned in your Python programs!

Related article: if you want to learn more about using Python for mathematics, have a look at this tutorial about calculating the square root of a number in Python.

I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!

Источник

Оцените статью