On Mon, Apr 20, 2015 at 11:21 AM, Alan Gauld <alan.ga...@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. _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor