Converting Decimal Number To Binary In Python 3
Solution 1:
Here are a few problems with your code:
rem = []
is inside the while loop, so in every loop iterationrem
will become[]
and in the end it will have only the last bit stored in it.The order of
//
and%
operation is wrong,//
will first truncate the data and%
will always produce0
. You need to reverse the order of those operations.reverse
is alist
method that does in place reversal and returnsNone
. That's why your code always printsNone
. So, you need to userem.reverse()
before the lastprint
line and printrem
normally.
After these changes, your code will look like this:
defbin_no():
global rem
n = int(input("Enter Number : ")) #Taking a Decimal Num
rem = []
while n >=1 : #Initiating a Loop to Convert Decimal To Binary using the (Divide By 2 Method).
rem.append(n%2)
n = n//2if n >=1: #Going back to the loop if input is invalid.print("Please enter a Valid Number")
bin_no()
rem.reverse()
print("Binary Number : ", rem) #Printing the result (the binary no. was stored in reverse order.)
bin_no()
Solution 2:
You don't need a recursive call here. It might produce some troubles.
def bin_no()
n = 0while n < 1:
n = int(input("Enter a Valid Number : "))
rem = []
while n > 0:
rem.append(n % 2)
n //= 2
rem.reverse()
print("Binary Number : ", rem)
Solution 3:
Let’s try to understand the decimal to binary conversion. The easiest technique to convert the decimal numbers to their binary equivalent is the Division by 2.
In Division by 2 technique, we continuously divide a decimal number by 2 and note the reminder, till we get 1 as our input value, and then we read the noted reminders in reverse order to get the final binary value.
Ways to Convert Decimal To Binary in Python
1. Using Custom Recursive Function
Code
# RecursiveFunctiontoconvertdecimaltobinary
def decimalToBinary(ip_val):
if ip_val >=1:
# recursivefunctioncall
decimalToBinary(ip_val //2)
# printing remainder fromeachfunctioncall
print(ip_val %2, end='')
# Driver Code
if __name__ =='__main__':
# decimalvalue
ip_val =24
# Calling special function
decimalToBinary(ip_val)
2. Using Built-in Function
Code
# Function to convert decimal to binary# using built-in python functiondefdecimalToBinary(n):
# converting decimal to binary# and removing the prefix(0b)returnbin(n).replace("0b", "")
# Driver codeif __name__ == '__main__':
# calling function# with decimal argumentprint(decimalToBinary(77))
3. Without using Built-in Function
Code
# Function to convert Decimal to BinarydefdecimalToBinary(val):
return"{0:b}".format(int(val))
# Driver codeif __name__ == '__main__':
print(decimalToBinary(77))
Post a Comment for "Converting Decimal Number To Binary In Python 3"