[Tutor] bin to dec conversion puzzlement

eryksun eryksun at gmail.com
Mon Apr 20 19:14:27 CEST 2015


On Mon, Apr 20, 2015 at 11:21 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>>
>> B = '11011101'
>> I = 0
>> while B:
>>      I = I * 2 + int(B[0])
>>      B = B[1:]
>
>> Both methods work but I just can't see how the first one does.
>
> The key is that the result gets multiplied by 2 each time
> so for an N bit number the leftmost digit winds up being
> effectively 2**N, which is what you want.

The loop iterates N times, so the leftmost digit is multiplied by 2 a
total of N - 1 times, i.e. B[0] * 2 ** (N - 1).

Another way to see this is that multiplying by 2 is a bitwise left
shift. Thus you can replace the multiplication and addition with
bitwise operations as follows:

    B = '11011101'
    I = 0
    while B:
        I = (I << 1) | int(B[0], 2)
        B = B[1:]
   assert I == 221

Shifting the values in like this may be more intuitively obvious.


More information about the Tutor mailing list