def flip_bit(number, n):

mask = 0b1 << (n-1)

result = number ^ mask

return bin(result)

print flip_bit(0b111, 2)

please, please explain why (n-1) and 0b1 is here

def flip_bit(number, n):

mask = 0b1 << (n-1)

result = number ^ mask

return bin(result)

print flip_bit(0b111, 2)

please, please explain why (n-1) and 0b1 is here

Hi cssrunner05147

We need those, because for instance if we want to reverse 4th bit, we need to get the binary number 1000

Remainder: x ^ 1 = ~x (x not), also x ^ 0 =x

When we put our number and the binary that we have created in an xor statement we will successfully reverse the desired bit.

if your question is why (n-1) but not n:

you have already put "1" there and if you shift it by (n-1) it will be n`th bit

if your question is why don`t we directly write 1000 for changing 4th or 100000 for changing 6th bit:

in order to make your program work for any desired bit to be changed

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