Friday, January 7, 2011

Bit Operation #5

How can we check whether a particular bit is ON (1) or OFF (0)?

bool checkBitOn(unsigned int num, unsigned int i)
{
return (num & (1 << i));
}


How can we turn OFF a particular bit in a number?

unsigned int turnBitOff(unsigned int num, unsigned int i)
{
return (num & (~(1 << i)));
}

For example, num = 00010111 and i = 4. (1<<4)==00010000 and ~(1<<4)==11101111. Hence, num&(~(1<<4))==00010111 & 11101111==00000111.

Then, how can we turn ON a particular bit in a number?

unsigned int turnBitOn(unsigned int num, unsigned int i)
{
return (num | (1 << i));
}

No comments: