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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With