def trans(x):
if x == 0: return [0]
bit = []
while x:
bit.append(x % 2)
x >>= 1
return bit[::-1]
Answer from Jun HU on Stack Overflowall 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}"
Videos
To convert from binary to decimal, just do:
int(binary_string, 2) # The 2 is the base argument from which we convert.
Demo:
>>> int('0b10110', 2)
22
Note- There are many issues with the code you are using to convert decimal to binary. If you are insistent on not using a built-in function for that purpose, you may be interested by this post:
Convert an integer to binary without using the built-in bin function
Although personally if I were to want to avoid the bin() function, I would do something like:
"{0:#b}".format(an_integer)
Demo:
>>> "{0:#b}".format(22)
'0b10110'
This is much more Pythonic than your current code.
this would be a lot easier no?
conv = str(input('what do you want to convert?'))
if conv == 'binary':
x = str(input('enter binary : '))
ansBin = int(x, 2)
print('decimal for binary ', x, ' is ', ansBin)
elif conv == 'decimal':
y = int(input('enter decimal : '))
ansDec = bin(y)[2:]
print('binary for decimal ', y, ' is ', ansDec)
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!