# Python program for decimal to binary conversion

## Decimal to binary conversion in Python

Here, in this page we will discuss the program for Decimal to binary conversion in python. A decimal number is a standard representation of integers or non-integers, decimal numbers are also called as numbers with base 10. Whereas in binary number system numbers are with base 10 and shows representation by 0 and 1.

### Methods discussed

• Method 1: Binary Bits stored in Array
• Method 2: Using mathematical operations to generate binary equivalent.

### Algorithm  ( Method 1 )

• Initialize a empty array as binaryArray
• while input number is greater then 0
• Append 1 if unit digit of num is odd else append 0
• Assign half the value of num to num
• Print all the values of  binaryArray

#### Python Code

Run
```def convertBinary(num):
binaryArray = []
while num>0:
binaryArray.append(num%2)
num = num//2
for j in binaryArray:
print(j, end="")

decimal_num = 21
convertBinary(decimal_num)```

#### Output

`Binary of 21 is : 10101`

### Algorithm  ( Method 2 )

• Initialize variables binary, i, rem and assign 0, 1, 0 respectively
• While input number is greater then zero run he loop
• rem equals to divisibility of input by 2
• num equals to half of num
• Add rem * i to binary
• Multiply i by 10
• return binary

#### Python Code

Run
```def convertBinary(num):
binary = 0
i, rem = 1, 0
while num != 0:
rem = num % 2
num = num // 2
binary += rem * i
i *= 10
return binary

decimal_num = 21
print("Binary of", decimal_num, "is : ", end="")
print(convertBinary(decimal_num))```

#### Output

`Binary of 21 is : 10101`

For similar questions click on the given button.

### Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

### 8 comments on “Python program for decimal to binary conversion”

• Yogesh

def dec_bin(n):
return ‘{0:b}’.format(int(n)
print(dec_bin(input()))

• Yogesh

Just one line:
def Dec_bin(n):

• priyarajswarnakar2018

def decimaltoBinary(num):
arr=[]
while num>0:
a=num%2
arr.append(a)
num=num//2

arr=arr[::-1]
for i in arr:
print(i,end=””)

num=int(input())
decimaltoBinary(num)

• Bharath

without built in function:
d=int(input())
b=”
i=0
while(d!=0):
r=d%2
s=str(r)
b+=s
d=d//2
i+=1
print(b[::-1])

• thedashinganon

n = int(input(“Enter Decimal Number : “))
res = 0
i = 1
while (n!=0):
rem = n % 2
res = res + rem * i
n= n//2
i = i*10
pre = ‘0b’
print(“Binary Value is “,(pre+str(res)))

• Sonal

num=int(input(“Enter the decimal number “))
sum=0
temp=num
base=1
while(temp):
digit=temp%2
sum+=digit*base
base*=10
temp//=2
print(“The binary value of {} is {}”.format(num,sum))

• Abhishek

a=int(input(“Enter the number :”))
c=[]
def decimal(n):
b=n%2
d=n//2
c.append(b)
if(d==0):
for i in c[::-1]:
print(i,end=””)
else:
decimal(d)

b=decimal(a)