Slip and Slide


#1

Hey people,
So i have been doing the bitwise operators and its quite a topic to get your head round and i seem to be doing okay, until this one came along.

It totally lost we with the n - 1, but i think i have an idea, let me show you an example to see if i am correct
If you have a 0b111 and you want it as a 0b101, the n will be 2, then you will put
flip_bit(0b111, 2)
does the 10th bit in 0b111 get reduced by 1(-1) which takes it to a 9 bit,
and now because it's no longer a 10 bit resulting in the 1 in the 10th place, it becomes a 0, making it 0b101
Does that make sense and am i right? oh i hope i am, as it was quite confusing, especially for new people

thank you for reading


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


#2

Hi @monkeyman1188,

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 1 bit.

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 1 by 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 1 by 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 1 in 0b1 to create the mask object. That is how we get ...

    mask = 0b1 << (n - 1)

After the mask is created, we can XOR the mask object with the object in which we wish to flip the bit.


#3

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