how to flip a bit at a specific position in an integer in any language
c, java, python
Solution
To flip one or more bits, use binary XOR. In your case, the appropriate XOR mask is `1` shifted `k` bits to the left.
In Python:
In [58]: 0b01101 ^ (1 << 2)
Out[58]: 9
The expression:
n ^ (1 << k)
is valid in C, Java, Python and a few other languages (provided the variables are appropriately defined).
Problem
I have an integer `n`, and I want to flip its `k`th bit (from the lowest) in its binary representation. How can I do it? For example, if I have `n=0b01101` and `k=2`, then the result is `0b01001=9` Any language is fine. Thank you.