Binary to dec python

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)

Читайте также:  Browser name in java

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.

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 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 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

Источник

Convert Binary to Decimal in Python

In this article, we will learn how to convert binary to decimal in Python. We will create custom functions to convert binary to decimal with different approaches.

Binary to Decimal Conversion

Binary numbers are a base-2 number system. It uses only two digits, 0 and 1. The binary number system is used in computers and other digital devices. For example, 10, 11, 101, etc.

Decimal numbers are a base-10 number system. It uses ten digits, 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. The decimal number system is used in everyday life. For example, 24, 45, 95, etc.

We can convert any binary number to a decimal number. To convert binary to decimal, we need to multiply each digit with its corresponding power of 2 and add the result. For example, 11002 = 1*2 3 + 1*2 2 + 0*2 1 + 0*2 0 = 8 + 4 + 0 + 0 = 1210

binary to decimal conversion

Examples of other conversions:

(11010)2 = 1*24 + 1*23 + 0*22 + 1*21 + 0*20 = (26)10 (1001)2 = 1*23 + 0*22 + 0*21 + 1*20 = (9)10 (101)2 = 1*22 + 0*21 + 1*20 = (5)10 (111)2 = 1*22 + 1*21 + 1*20 = (7)10 (1010)2 = 1*23 + 0*22 + 1*21 + 0*20 = (10)10 (1101)2 = 1*23 + 1*22 + 0*21 + 1*20 = (13)10 (1111)2 = 1*23 + 1*22 + 1*21 + 1*20 = (15)10 (10001)2 = 1*24 + 0*23 + 0*22 + 0*21 + 1*20 = (17)10

# Method 1: Using int() Function

We can use the int() function to convert binary to decimal.

The int() function takes two arguments, the first is the number to be converted and the second is the base of the number. The default base is 10. So, we need to pass 2 as the second argument to convert binary to decimal.

Note : The number to be converted (decimal number here) should be passed as a string.

num = input("Enter a binary number: ") num = str(num) # convert to decimal dec = int(num, 2) print("The decimal value of " + str(num) + " is " + str(dec))
Enter a binary number: 110110 The decimal value of 110110 is 54

# Method 2:

In the last method, we used a built-in python function to convert binary to decimal. Now we are going to create our own program that converts a binary number to a decimal.

Algorithm

  1. Create a python function that takes a decimal number as an integer.
  2. Inside this define a variable dec and assign it 0. It stores decimal values.
  3. Define another variable named mul and assign it 1. This will be used to multiply with the current bit of binary digit.
  4. Run a loop until the binary number becomes 0. In each loop multiply the multiple with the last bit, divide the number by 10 and multiply the mul variable by 2.
  5. Finally, return the decimal value.
def bin_to_dec(n): dec = 0 mul = 1 while n: dec = dec + (n % 10) * mul n //= 10 mul *= 2 return dec num = int(input("Enter a binary number: ")) print("The decimal value of " + str(num) + " is " + str(bin_to_dec(num)))
Enter a binary number: 11001 The decimal value of 11001 is 25

binary to decimal example

# Method 3:

In this method, we will use enumerate() function with for loop to go through each digit of the binary number and convert it to decimal.

Algorithm

  1. Create a function. Inside convert the input number to a string first.
  2. Reverse the string using [::-1] slicing.
  3. Define a variable dec and assign it 0. It stores decimal values.
  4. Run a for loop using enumerate() function to go through each digit of the binary number.
  5. Inside the loop, convert each digit to an integer and multiply the digit with 2 i where i is the index of the current digit and add it to the dec variable.
  6. Finally, return the decimal value.
def bin_to_dec(n): # convert the input to string n = str(n) # reverse string # because we will start from the right n = n[::-1] # initialize result dec = 0 # loop through the string for i, digit in enumerate(n): # multiply each digit by 2^i dec += int(digit) * (2**i) return dec num = input("Enter a binary number: ") print(bin_to_dec(num))

binary to decimal example

Enter a binary number: 10011 19

# Method 4: Using Recursion

Let’s use recursion to convert binary to decimal.

For this, we need to create a base case and a recursive case. In the base case, we check if the binary number is 0. If it is, we return 0. Otherwise, we return the remainder of the binary number divided by 10 plus 2 times the function itself with the binary number divided by 10.

# binary to decimal recursive def bin2dec(bin): if bin == 0: return 0 else: return bin%10 + 2*bin2dec(bin//10) num = int(input("Enter a binary number: ")) print("The decimal value of " + str(num) + " is " + str(bin2dec(num)))

binary to decimal example

Enter a binary number: 10011 The decimal value of 10011 is 19

Источник

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