I am trying to create a decimal to binary converter. The user inputs their value, and the amount is divided by two each time and added to the invertedbinary
list. The amount is then converted back into an integer, to be divided by two again and so on.
value = int(input("Please enter the decimal value to be converted to binary."))
invertedbinary = []
while value >= 1:
value = (value/2)
invertedbinary.append(value)
value = int(value)
print (invertedbinary)
for n,i in enumerate(invertedbinary):
if i == isinstance(invertedbinary,int):
invertedbinary[n]=0
else:
invertedbinary[n]=1
print (invertedbinary)
Let's say I input the number seventeen. This is the output:
[8.5]
[8.5, 4.0]
[8.5, 4.0, 2.0]
[8.5, 4.0, 2.0, 1.0]
[8.5, 4.0, 2.0, 1.0, 0.5]
[1, 1, 1, 1, 1]
So we can tell that from the last line of ones, my isinstance
attempt did not work. What I want to be able to do, is that if the amount is anynumber.5 then to display it as a 1, and if it is a whole number to display as a zero. So what it should look like is [1, 0, 0, 0, 1]
. Ones for each float value, and zeroes for the integers.
What can I use instead of is instance
to achieve this?
For anyone wondering, I've called it invertedbinary
because when printed invertedbinary
needs to be flipped around and then printed as a string to display the correct binary value.