The part that converts the binary is int. From the documentation:
if base is given, then x must be a string,
bytes, orbytearrayinstance representing an integer literal in radix base.
This means that int accepts a string representing an integer, that you tell it the base of. E.g. here we give it "11", and tell it this is in base 2, so it returns the integer 3 in decimal.
>>> int("11", 2)
3
Note that when supplying the base argument, you have to give a string:
>>> int(11, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int() can't convert non-string with explicit base
And you can't use digits that are invalid in the given base:
>>> int("21", 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 2: '21'
Answer from Calum You on Stack OverflowConvert decimal input to 8 bit binary
Write a program in Python to convert an 8-bit binary number to a
decimal number. This application will use loops and conditions to
accomplish the task. If the input is less than or greater than 8
bits or anything other than 0s or 1s, you can exit with an error
message.
(Can you please do it AS SIMPLE AS YOU CAN as I am a beginner
and if you use things that
python - Converting binary to decimal integer output - Stack Overflow
python - Converting a calculated decimal number into 8 bit binary - Stack Overflow
Hi all i'm very new to coding (a few weeks) and Python and was wondering if there is a way to get an input of a decimal number and convert it to 8 bit binary. Currently using the Thonny IDE
You can use int and set the base to 2 (for binary):
>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> int(binary, 2)
25
>>>
However, if you cannot use int like that, then you could always do this:
binary = raw_input('enter a number: ')
decimal = 0
for digit in binary:
decimal = decimal*2 + int(digit)
print decimal
Below is a demonstration:
>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> decimal = 0
>>> for digit in binary:
... decimal = decimal*2 + int(digit)
...
>>> print decimal
25
>>>
Binary to Decimal
int(binaryString, 2)
Decimal to Binary
format(decimal ,"b")
ps: I understand that the author doesn't want a built-in function. But this question comes up on the google feed even for those who are okay with in-built function.
You do have to print the value:
>>> print(bin(160)) # This version gives the 0b prefix for binary numbers.
0b10100000
>>> print(format(160,'08b')) # This specifies leading 0, 8 digits, binary.
10100000
>>> print('{:08b}'.format(160)) # Another way to format.
10100000
>>> print(f'{160:08b}') # Python 3.6+ new f-string format.
10100000
One option for printing it would be to slice off the 0b portion of the result, which I assume is what you mean when you say you are having problems with the bin function.
Try this:
print(bin(calculatedanswer)[2:]))