23

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.

5 Answers5

36

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).

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
9

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
Constablebrew
  • 816
  • 1
  • 7
  • 23
3

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);
Ion
  • 334
  • 3
  • 15
  • Alternatively, instead of `pow(2,k)`, you can use `(n >> k) & 1` to find the value at position **k** when **n** is an integer. Resulting in a RSHIFT instead of a function call, same can be said for the power operator`**`, though performance wise this is of little concern. – holmberd Feb 17 '18 at 17:42
2

Here's how you'd do it in C:

n ^ (1 << k)
Kevin
  • 1,179
  • 7
  • 18
0

(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"
Lewis Miller
  • 105
  • 6