0

I'm attempting to get a binary string from a user and convert it into decimal. However when I do this I am not getting the right total, I'm getting numbers bigger than what their decimal conversion is and I cannot understand why for some reason... Thank you.

I have tried to change around the variables

binary_str = input("Please input the binary string: ")

Power = 7
Total = 0

for char in binary_str:
    product = int(char) * 2**Power
    Total += product
    set_power = Power - 1


print(Total)

The output was 512 when the number was supposed to be in the 200s

  • Use [raw_input](https://stackoverflow.com/questions/3800846/differences-between-input-and-raw-input) instead, otherwise you'll get a evaluated object based on your input. If you're actually using python3. – Torxed Jan 30 '19 at 12:23
  • Shouldn't you use `Power = Power - 1`? You are not using `set_power` anywhere – Sheldore Jan 30 '19 at 12:34

2 Answers2

0

You dont need to do this, int will do this for you, try this:

binary_str = input("Please input the binary string: ")
t = int(binary_str, 2)

t will be your expected result.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
0

The following will work for your purpose:

binary_str = input("Please input the binary string: ")
power = len(binary_str)-1
total = 0

for char in binary_str:
    total += int(char) * 2**power
    power -=1
print(total)

In our solution set_power has nothing to do with Power and the value of Power does not change in each iteration. So, the value multiplied in each digit would be 2**7 for all digits. If you want to fix it consider Power-=1 like the shown code.

Farzad Vertigo
  • 2,458
  • 1
  • 29
  • 32