Reputation: 1
I have created a basic program for converting 8-bit binary to decimal, but when I run the program, it works backwards, e.g. if I enter the binary number '00000001'
the program will return 128
. Here is my code:
binaryvalue=input("Please enter your 8 bit binary number.")
binaryvalue=str(binaryvalue)
if len(binaryvalue) <= 8:
print("Your number is accurate.")
value_index=0
total=0
print("Your number is valid.")
for i in range(len(binaryvalue)):
total = total + (int(binaryvalue[value_index])) * 1 * (2**(value_index))
value_index = value_index+1
print("Your decimal number is: "+str(total))
Upvotes: 0
Views: 370
Reputation: 2268
So, as mentioned by jonrsharpe and Moe
reverse the input:
binaryvalue = str(binaryvalue)[::-1]
or, you can place the offset in your power:
total = total + (int(binaryvalue[value_index])) * 1 * (2**(len(binaryvalue)-value_index-1))
Both are essentially doing the same thing though.
Upvotes: 1