Home > Enterprise >  How to convert a decimal number into a binary list with fixed number of bits in Python 3.8?
How to convert a decimal number into a binary list with fixed number of bits in Python 3.8?

Time:11-09

Suppose I have the decimal number 8, and I want to conver it into a binary list of length 8. It means if I give input as 8, I should get output as [0,0,0,0,1,0,0,0]. I am looking for an inbuilt command in python that can do that in a very short time (in nano-seconds).

I have tried the foolowing comman which is giving me error:

[int(x) for x in list('{0:8b}'.format(8))]

The error I am getting is

ValueError: invalid literal for int() with base 10: ' '

CodePudding user response:

You can do with list comprehension.

>>> [int(i) for i in bin(8)[2:].zfill(8)]
[0, 0, 0, 0, 1, 0, 0, 0]

bin(8) return the binary representation of an integer 8 and it's always prefixed with 0b. So bin(8)[2:] is to remove these first two characters(ie, 0b). And then you can use .zfill(8) to pad a numeric string with zeros on the left(with the given width 8)

CodePudding user response:

You could build an f-string then iterate over that with map() as follows:

n = 8

lst = list(map(int, f'{n:08b}'))

print(lst)

Output:

[0, 0, 0, 0, 1, 0, 0, 0]

CodePudding user response:

First:

[function(item) for item in list]

Will go through all items in list, and return a list witch all items handled by function.

Second:

'[index]:[width][type]'.format(input)
'{0:8b}'.format(8)

Means convert input in index 0:8 to binary string 1000, and fill space until width is 8. So the result of '{0:8b}'.format(8) is 1000.(Please search .format() for more informations)

So what it's trying to do is:

[int(x) for x in list('    1000'.format(8))]

The error you got is because you are trying to parse space(' ') to int.

You can try: Fill width with 0:

[int(x) for x in list('{0:08b}'.format(8))]
  • Related