I have an integer n, and I want to flip its kth 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.
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).
Left-shift the number 1 the number of digits you need, and then XOR the number.
JavaScript:
var num = 6, k = 2;
num = num ^ (1 << k);
What is happening:
num = 0b01101 XOR (0b00001 << 2)
num = 0b01101 XOR 0b00100
num = 0b01001
 
    
    In c you just do this to toggle it:
n ^= 1 << k;
but there are other ways of doing it like:
n |= ( 1 << k);
This shifts bit k to 1
Now if you want to flip the bit you can do an if statement with a unary and to see how you need to flip it
number = pow(2,k)    
if((number & n) != number)
    //this means that it's a 0 at position k
    n |= ( 1 << k);
else
    //this means that it's a 1 at position k
    n &= ( 0 << k);
 
    
    (for googlers) here is how you can do it in VB6 without shifting
'flips a bit to the opposite of its current value
'1 based, left to right
Function FlipBit(ByVal FlipByte As Byte, ByVal bPosition As Byte) As Byte
    FlipBit = FlipByte Xor (2 ^ (8 - bPosition))
End Function
'example
 MyByte = 255
'mybyte is now "11111111"
 MyByte = FlipBit(MyByte,2)
'mybyte is now "10111111"
