-1

My teacher was teaching us on how to convert binary to number manually. I found it boring and wrote a simple python script to automatically do the above conversion. The code I wrote is given below -

def bin2num():
  i=input("Enter a binary - ")
  n=len(i)- 1
  f=0
  for e in i:
   f=f+int(e)*(2^n)
   n=n-1
  print(f)

Like for example if the binary is 10111, we convert it into number by doing something like this -

1 * 2^0 + 1 * 2^1 + 1 * 2^2 + 0 * 2^3 + 1 * 2^4 = 1+2+4+0+16 = 23

But my script is returning 11, instead of 23.

I asked my professor but unfortunately he was unable to find out the error, searching the internet gave me many answers but I wanted to understand why this failed to compute correct answer and how to approach the problem, thus filed this question.

I will be more than happy if any developer can take out his or her precious time and help me out :)

0x48piraj
  • 395
  • 3
  • 12
  • 1
    tangent: input() returns a string - not need to stringify it. – Patrick Artner Jul 29 '18 at 19:16
  • I assume you know that the `int` constructor can handle binary input... But anyway, if you want to do this manually there's a way to do it without exponentiation. Can you figure it out? – PM 2Ring Jul 29 '18 at 19:30

1 Answers1

1

The ^ operator is the binary XOR operator. Use ** instead.

f=f+int(e)*(2**n)
Bob
  • 26
  • 1