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><code>0b010001110</code> is <em>already</em> an integer with the decimal value of 142. If you really want to do your own binary conversion function you'll need to pass the binary arg in as a string, eg '010001110', or as a list of bits, which can be strings, integers, or even the boolean values <code>True</code> and <code>False</code>. </p>

<p>Once you have the <code>str</code> vs <code>int</code> input issue resolved, there's a simpler way to do the conversion. There's no need to mess around with exponents: in the loop just bit-shift the current result one place to the left and insert the next bit. Like this: </p>

<pre><code>def bin_to_int(bits):
    result = 0
    for b in bits:
        result = (result &lt;&lt; 1) | int(b)
    return result

# Test
data = [
    '0',
    '1',
    '110',
    '001101',
    '10001110', 
    '000010001110', 
    '11000000111001',
]

for bits in data:
    print(bits, int(bits, 2), bin_to_int(bits))
</code></pre>

<p><strong>output</strong></p>

<pre><code>0 0 0
1 1 1
110 6 6
001101 13 13
10001110 142 142
000010001110 142 142
11000000111001 12345 12345
</code></pre>

<p>My test code uses the built-in <code>int</code> constructor to do the conversion as well, to verify that my <code>bin_to_int</code> function is performing correctly.</p>

<p>This line, which does most of the work, uses bitwise operators, </p>

<pre><code>result = (result &lt;&lt; 1) | int(b)
</code></pre>

<p>but you can implement it with "normal" arithmetic operators, if you like</p>

<pre><code>result = result * 2 + int(b)
</code></pre>

python python-3.x