xxxxxxxxxx
a = 10
#this will print a in binary
bnr = bin(a).replace('0b','')
x = bnr[::-1] #this reverses an array
while len(x) < 8:
x += '0'
bnr = x[::-1]
print(bnr)
xxxxxxxxxx
a=10
b=format(a,'b')
print(b)
Output:
1010
a=10
b=format(a,'08b')
print(b)
Output:
00001010
xxxxxxxxxx
bin(6)[2:]
'110'
# bin() converts to binary, but leaves 0b as the start of the string, remove it
xxxxxxxxxx
======= Convert Decimal to Binary in Python ========
my_int = 10;
#Method 1: using bin
n1 = bin(my_int).replace("0b", "") #1010
or n1 = bin(my_int)[2:]
#Method 2: using format
n2 = "{0:b}".format(my_int)
or n2 = format(my_int, 'b') #1010
xxxxxxxxxx
"Convert decimal to 8 digit binary"
def DecimalToBinary8(number):
return format(number, "08b")
"Convert decimal to 16 digit binary"
def DecimalToBinary16(number):
return format(6, "016b")
print("8 Digit Binary Representation of 6")
print(DecimalToBinary8(6)) #Prints '00000110'
print("16 Digit Binary Representation of 6")
print(DecimalToBinary16(6)) #Prints '0000000000000110'
xxxxxxxxxx
DecimalToBinary(num):
if num >= 1:
DecimalToBinary(num // 2)
print num % 2