convert int to binary python 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: how to convert decimal to binary python
a = 5
print(bin(a))
Example 3: 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 4: how to get the binary value in python
bin(19)
def binary(num):
array = []
while(num > 0):
sol1 = num / 2
check = sol1 - int(sol1)
if(check > 0):
array.append("1")
num = sol1 - 0.5
else:
array.append("0")
num = sol1
while(len(array) < 4):
array.append("0")
array = array[::-1]
string = ''.join(array)
return string