Bitwise Operators: Bitwise Operations Tricks

1. To check if the number is even or odd

num & 1

2. To clear the lowest set bit of x

num & (num - 1)

3. Divide by 2

num >> 1

4. Get the lowest set bit

num & ~(num - 1)

5. Multiply by 2

num <<= 1

6. Change to lower case

char &= '_'

7. Change to upper case

char |= '_'

8. Count set bits

int count = 0;
while (num)
{
    num &= (num-1);
    count++;
}
return count;

9. Find the last set bit

log2(num & -num)+1;

10. Turn on kth bit

return num | (1 << (k - 1));

11. Turn off kth bit

return num & ~(1 << (k - 1));

12. Toggle kth bit

return num ^ (1 << (k - 1));

13. Check kth bit is set or not

return (num & (1 << (k - 1))) != 0;
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *