14. Slip and Slide - Why do I have to put 0b1?


I thought I had to put number which would be inputed where I put 0b1 in that code bellow. But it wasn't working so I came in here and everybody was putting 0b1, so I did it too and it work. But why?

def flip_bit(number, n):
    mask = (0b1 << n - 1)
    result = number ^ mask
    return bin(result)


0b1 is the binary integer, 1. If this code shifts the 1 bit two magnitudes to the left. it is the same as multiplying by 2, twice. The result should be 4, or 0b100.


Let us assume that number = 186 (0b10111010) and we want to flip the third bit from the right.

From the exercise about the XOR operator you should know that we need mask 0b100 to achieve this task. And that's exactly what (0b1 << 3 - 1) will return.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.