Home > Software engineering >  how to convert decimal to binary with 0 in python
how to convert decimal to binary with 0 in python

Time:09-23

so i want to convert all list decimal to binary contain with 0. but what i make its have int type and the all the 0 is gone.

input = [6, 7, 2, 11, 14, 15, 10, 3, 6, 7, 2, 11, 14, 15, 10, 3]

output = [110, 111, 10, 1011, 1110, 1111, 1010, 11, 110, 111, 10, 1011, 1110, 1111, 1010, 11]

can someone fix my code so it have 0 in the front? like 00000110 its mean 6

here's my code:

def dec_to_bin(x):
    print(x)
    for a in range(0, len(x)):
        keluar = x[a]
        biner = int(bin(keluar)[2:])
        x[a] = biner
    return x

CodePudding user response:

You need the str type to retain zeros. You can use a format string to instruct the number to display as 8-digit-with-leading-zero binary:

def dec_to_bin(x):
    return [f'{a:08b}' for a in x]

result = dec_to_bin([6, 7, 2, 11])
print(result)
print(' '.join(result))

Output:

['00000110', '00000111', '00000010', '00001011']
00000110 00000111 00000010 00001011

CodePudding user response:

zfill function will fill leading zero on the left. You can specify the digit on the parameter:

x[a] = biner.zfill(8)
  • Related