Some interesting read on Bit Twiddling: setting and resetting(clearing) bit

a | b…. a & c…….a^b…..~a*(a^b)…..

If above criptic notations make some sense for you and you enjoyed reading above then here is some resource for you. I was actually searching way to set or reset a bit on a number. Finally i got some solution to share:

Setting a bit:
number = number | (1 << n); //(it will set (n+1) th bit)

e.g.:
num1 = 32;//100000
n = 2;
num2 = num1 | (1<<n);//num2=36 (100100)…it is setting 3rd bit

Resetting(Clearing) a bit:
number = number & ~(1<<n); //it will clear (n+1)th bit.

e.g.:
num1 = 34; //100010
n = 1;
num2 = num1 & ~(1<<n); //num2=32(100000)…it is clearing 2nd bit

using above we can write function to set and reset bit:


/*set the bit at bitPos*/
int setBit(int num,int bitPos)
{
  return num | (1<<(bitPos-1));
}

and to clear:

/*reset(clear) the bit at bitPos*/
int resetBit(int num, int bitPos)
{
  return num & ~(1<<(bitPos-1));
}

Here I have found some good resource on bit twiddling:

Bit Twiddling Hacks

Some thing more advance:

Advanced bit manipulation-fu

reference:

1. Stack Overflow