Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert binary to list of digits Python

I have the following scenario:

x = 0b0111

I would like to convert this value to:

y = [0, 1, 1, 1]

When I convert x = 0b1001, I can get y = [1, 0, 0, 1], but when I try to do the same for x = 0b0111, and then convert back with str(bin(y)) - I seem to lose the leading 0, and get 0b111.

Any suggestions?

like image 859
user1656238 Avatar asked Oct 26 '12 05:10

user1656238


1 Answers

Updated for f-String:

x = 0b0111
y = [int(i) for i in f'{x:04b}']

y = [0, 1, 1, 1]

or:

x = 0b0111 # binary representation of int 7
n_bits = 4 # desired bits' len
y = [int(i) for i in f'{x:0{n_bits}b}']

Will populate a list of minimum len n-bits filling the list with leading 0's

like image 118
JFMoya Avatar answered Oct 03 '22 21:10

JFMoya