python convert to binary code example
Example 1: convert int to binary python
def decimalToBinary(n):
return bin(n).replace("0b", "")
if __name__ == '__main__':
print(decimalToBinary(8))
print(decimalToBinary(18))
print(decimalToBinary(7))
Output:
1000
1001
Example 2: python int to binary
print('{0:b}'.format(3))
print('{0:8b}'.format(3))
print('{0:08b}'.format(3))
def int2bin(integer, digits):
if integer >= 0:
return bin(integer)[2:].zfill(digits)
else:
return bin(2**digits + integer)[2:]
print(int2bin(3, 6))
Example 3: how to convert decimal to binary python
a = 5
print(bin(a))