acubal - 3 months ago 22

Python Question

Okay. first of all i know there is a built-in function converting binary to decimal but i thought i challenge myself and make my own.

Here are the codes....

`def binaryToDecimal(binary):`

binaryList = list(str(binary))

exponent = len(binaryList) - 1

decimal = 0

for char in binaryList:

bit = int(char)

decimal += bit * (2 ** exponent)

exponent -= 1

print(decimal)

The problem is, i know if i want to begin my binary with 0, i have to use 0b prefix to avoid an invalid token but it leads me to a problem. It doesn't convert the last 1 on the left

`binaryToDecimal(0b010001110)`

So it outputs 14 instead of 142

How do i fix that? Also is there a way i can just say

`binaryToDecimal(010001110)`

without getting an invalid token without using 0b prefix?

I'm using Python 3.5

Answer

Youre problem is mainly `binaryList = list(str(binary))`

.
`str(0b010001110)`

returns `'142'`

, not `'0b101010'`

as you might expect.

Consequently, `binaryList`

is `['1', '4', '2']`

.

A coincidence made that `1 * 2**2 + 4 * 2**1 + 2`

equals 14, which gives the impression that you're function don't treat the last digit.

But, if you're running you're function with `0b101010`

as input, you get `10`

.

A solution to get the binary representation as string is to pass to `format`

:

```
list("{0:b}".format(0b010001110))
```

Which returns

```
['1', '0', '0', '0', '1', '1', '1', '0']
```