AAGW - 9 months ago 35

Python Question

`value = input("Enter the binary value to convert to a decimal number.")`

prod = 0

power = 0

ans = 0

for i in range (int(value)):

prod = ((int(value[*right most digit here*])) * ((2**power)))

ans = prod + ans

prod = 0

power + 1

else:

print (ans)

I am trying to create a binary calculator.

I believe I have the power part of the equation working as it begins with 2 ^ 0, then 2 ^ 1 for the next digit and so on. But I am having trouble getting the first part of the equation, the right most digit of the value inputted.

So let's say, 0101 was inputted. I want 1 * ( 2 ^ 0 ) in the first loop, 0 * ( 2 ^ 1) in the second loop, and so on; right to left. So with how indexing works in Python, how can I reverse index it so [4] is in the first loop, then [3] in the second loop, and so on.

Thanks for help.

Answer Source

However there are better options available, i am assuming you are clearing your basics. Following can be the options:

*Note : You should use len(value) instead of int(value) in the loop.*

```
# 1. When starting the loop from 0 (i.e. i=0). you can use ( len(value) - i )th index.'
for i in range (len(value)):
prod = ((int(value[len(value) - i - 1])) * ((2**power)))
ans = prod + ans
prod = 0
power = power + 1
# 2. Python also supports negative indexing, So you may run a loop from -1 to -len(value).
for i in range (-1,-len(value) - 1,-1):
prod = ((int(value[i])) * ((2**power)))
ans = prod + ans
prod = 0
power = power + 1
# 3. You can reverse the whole string in your first step and then loop from 0 to len(value)-1.
value = reversed(value)
for i in range (len(value)):
prod = ((int(value[i])) * ((2**power)))
ans = prod + ans
prod = 0
power = power + 1
```

But there are some bugs in the code (or may be lack on information). This code works only for unsigned integers. If you want it to work on signed numbers as well, you have to take 2's complement into consideration. Below is a very simple code that works with signed numbers too (in case needed):

```
#convert binary string into decimal value. Works on 2's complement.
def binToDecimal(s):
neg = False
if s[0] == '1':
s = twosComp(s)
neg = True
#compute the decimal value
val = reduce(lambda x,y : int(x)*2+1 if y=='1' else int(x)*2,'0'+s)
#negate the value if the first bit is 1
return -val if neg else val
#return the 2's complement string
def twosComp(s):
s = list(s[::-1])
#take 1's complement
s = ['1' if i=='0' else '0' for i in s]
#take 2's complement
for i in range(len(s)):
if s[i] == '0':
#no carry will be generated in this case, so we break it.
s[i] = '1'
break
else:
s[i]='0'
# return 2's complement string
return ''.join(map(str,s))[::-1]
```