Some uses of bit manipulation in c or c++ programming is second blog series ofbit manipulation in c or c++“.

how to check whether nth bit is set or not?

If a given number is 17. The binary equivalent of decimal number 17 is 10001. To check whether 4th bit is set or not set , check the condition ( 17 & ( 1 << 4 ). if the condition is true ,the 4th bit is set otherwise not set.

How to set Kth bit ?

  • Left shift the integer by kth.
  • or with the number.

how to clear kth bit?

Use the bitwise AND operator (&) to clear a bit. number &= ~(1 << x); That will clear bit x. You must invert the bit string with the bitwise NOT operator (~), then AND it.

how to toggle kth bit?

The XOR operator ( ^ )  is used to toggle a bit. number ^= 1 << x; That will toggle bit x

Click here to learn advance uses of bit manipulation in competitive programming.

Ref:

https://www.quora.com/How-do-you-set-clear-and-toggle-a-single-bit-in-C




Related Contents to follow