a = 0b101
tenth bit mask
mask = (0b1 << 9)
one less than ten
desired = a ^ mask
let's say that l want to turn on the 10th bit from the right of the integet a
instead of writing out the entire number,we slide a bit over using the << operstor.
we use 9 because we only need to slide the mask nine places over from the first
bit to reach the tenth bit .
1.define a function called flip_bit that takes the inputs(number,n).
2.filp the nth bit (with the ones bit being the first bit) and score it inresult.
3.return the result of calling bin(result).
def flip_bit(number,n)
result = (0b1 << n-1) ^ number
return bin(result)
left bit shift(<<)
0b000001 << 2 ==0b000100(1<<2 == 4)
122=4
0b000101 << 3 == 0b101000(5 << 3 ==40)
522*2 =40
right bit shift(>>)
0b0010100 >> 3==0b000010(20>>3=2)
20%3%2余2
0b0000010 >>2 == 0b0000000(2>>2 ==0)
2%2%2余0
mathematically equivalent to floor dividing and multiplying by 2(respectively) for every time you shift
but it's often easier just to think of it as shifting all the 1s and 0s left or right by the specified number of slots.