How to avoid invalid token when converting binary to decimal
<p>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. </p>

<p>Here are the codes....</p>

<pre><code>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)
</code></pre>

<p>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</p>

<pre><code>binaryToDecimal(0b010001110)
</code></pre>

<p>So it outputs 14 instead of 142</p>

<p>How do i fix that? Also is there a way i can just say </p>

<pre><code>binaryToDecimal(010001110) 
</code></pre>

<p>without getting an invalid token without using 0b prefix?</p>

<p>I'm using Python 3.5</p>

<p>Youre problem is mainly <code>binaryList = list(str(binary))</code>.
<code>str(0b010001110)</code> returns <code>'142'</code>, not <code>'0b101010'</code> as you might expect.</p>

<p>Consequently, <code>binaryList</code> is <code>['1', '4', '2']</code>.</p>

<p>A coincidence made that <code>1 * 2**2 + 4 * 2**1 + 2</code> equals 14, which gives the impression that you're function don't treat the last digit.</p>

<p>But, if you're running you're function with <code>0b101010</code> as input, you get <code>10</code>.</p>

<p>A solution to get the binary representation as string is to pass to <code>format</code>:</p>

<pre><code>list("{0:b}".format(0b010001110))
</code></pre>

<p>Which returns</p>

<pre><code>['1', '0', '0', '0', '1', '1', '1', '0']
</code></pre>

python python-3.x