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.

#include<stdio.h>

int main() {

	int a = 17; /*10001 */
	int kth = 4;
	if( a & ( 1 << kth))
	{
		printf("%dth bit is set\n",kth);
	}
	else
	{
		printf("%dth bit is not set\n",kth);
	}
	return 0;
}

How to set Kth bit ?

  • Left shift the integer by kth.
  • or with the number.
#include<stdio.h>

int main() {

	int a = 17; /*10001 */
	int kth = 3;

    /* kth=3 bit is not set */
    /* now set kth bit */
	a = a | ( 1 << kth);

	if( a & ( 1 << kth)) // check whether kth bit is set
	{
		printf("%dth bit is set\n",kth);
	}
	else
	{
		printf("%dth bit is not set\n",kth);
	}
	return 0;
}

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