For this exercise, as well as others, the positions of the bits are counted from right to left, with the right-most bit being considered the first bit. Accordingly, the number
0b111 has only a first, second, and third bit.
In this exercise, we need to flip a single specific bit. To do so, we choose an operation that is best for flipping a
0 bit to a
1 bit or a
1 bit to a
0 bit. That operation would be XOR(
^)ing the bit to be flipped with a
To perform the operation, we create a
mask object that has the
1 bit in the same position as the bit to be flipped. We start with
0b1, which has a
1 in the first position. Now, we need to slide that bit to the position of the bit to be flipped.
Let's consider the case where the first bit is the one to be flipped.
0b1 already has the
1 in the first bit position, so to create the
mask object, we slide the
0 positions to the left, which is really not sliding it at all. The number of positions of the sliding is
1 less than the position of the bit to be flipped.
Let's consider the case where the third bit is the one to be flipped. In that case, we need to slide the
2 positions to the left. Again, that is
1 less than the position of the bit to be flipped. In fact, the number of positions by which we need to slide the
1 bit to create the
mask object is always
1 less than the position of the bit to be flipped. Therefore, if
n represents the position of the bit to be flipped, then
n - 1 is the number of positions to the left by which we need to slide the
0b1 to create the
mask object. That is how we get ...
mask = 0b1 << (n - 1)
mask is created, we can XOR the
mask object with the object in which we wish to flip the bit.