1# Python program to convert decimal to binary
2
3# Function to convert Decimal number
4# to Binary number
5def decimalToBinary(n):
6 return bin(n).replace("0b", "")
7
8# Driver code
9if __name__ == '__main__':
10 print(decimalToBinary(8))
11 print(decimalToBinary(18))
12 print(decimalToBinary(7))
13
14Output:
151000
161001
1 bin(6)[2:]
2'110'
3
4# bin() converts to binary, but leaves 0b as the start of the string, remove it
5
1a = 10
2#this will print a in binary
3bnr = bin(a).replace('0b','')
4x = bnr[::-1] #this reverses an array
5while len(x) < 8:
6 x += '0'
7bnr = x[::-1]
8print(bnr)
1print('{0:b}'.format(3)) # '11'
2print('{0:8b}'.format(3)) # ' 11'
3print('{0:08b}'.format(3)) # '00000011'
4
5def int2bin(integer, digits):
6 if integer >= 0:
7 return bin(integer)[2:].zfill(digits)
8 else:
9 return bin(2**digits + integer)[2:]
10print(int2bin(3, 6)) # '000011'