Playing with Kth bit

1) Turn Off kth bit in a number

int turnOffKthBit(int n, int k) {
    return n & ~(1 << (k - 1));
}

2) Turn On kth bit in a number

int turnOnKthBit(int n, int k) {
    return n | (1 << (k - 1));
}

3) Check if kth bit is set for a number

bool isKthBitSet(int n, int k) {
    return (n & (1 << (k - 1))) != 0;
}

4) Toggle the kth bit

int toggleKthBit(int n, int k) {
    return n ^ (1 << (k - 1));
}

Please refer this article for more bit hacks.


 



Bit Tricks for Competitive Programming

In competitive programming or in general, some problems seem difficult but can be solved very easily with little concepts of bit magic. We have discussed some tricks below in the previous post.
Bitwise Hacks for Competitive Programming

Similar Reads

One-Liner Hacks of Bit Manipulation:

...

Playing with Kth bit:

1) Turn Off kth bit in a number...