You can probably use the builtin bin function:
bin(8) #'0b1000'
to get the list:
[int(x) for x in bin(8)[2:]]
Although it seems like there's probably a better way...
Answer from mgilson on Stack OverflowYou can probably use the builtin bin function:
bin(8) #'0b1000'
to get the list:
[int(x) for x in bin(8)[2:]]
Although it seems like there's probably a better way...
Try this:
>>> list('{0:0b}'.format(8))
['1', '0', '0', '0']
Edit -- Ooops, you wanted integers:
>>> [int(x) for x in list('{0:0b}'.format(8))]
[1, 0, 0, 0]
Another edit --
mgilson's version is a little bit faster:
$ python -m timeit "[int(x) for x in list('{0:0b}'.format(8))]"
100000 loops, best of 3: 5.37 usec per loop
$ python -m timeit "[int(x) for x in bin(8)[2:]]"
100000 loops, best of 3: 4.26 usec per loop
Convert decimal to binary in python - Stack Overflow
Converting from decimal to binary in Python
converting a list consist of decimal numbers to binary in python - Stack Overflow
How to Convert list of binary number to decimal in python without using any inbuilt function?
Videos
all numbers are stored in binary. if you want a textual representation of a given number in binary, use bin(i)
>>> bin(10)
'0b1010'
>>> 0b1010
10
Without the 0b in front:
"{0:b}".format(int_value)
Starting with Python 3.6 you can also use formatted string literal or f-string, --- PEP:
f"{int_value:b}"
Would someone be willing to help me (total beginner) understand how this converts decimal values to binary? Maybe just by explaining what happens line by line?
def dec2bin(n):
if n > 1:
dec2bin(n//2)
print(n % 2, end="")It's just not intuitive at all for me :/
Any help would be greatly appreciated!
For example: [1,0,0,1] should give output 9