Friday, January 17, 2014

Checking if a bit is on or off without affecting other bits

Let's say that we have a bit string of 1101 and we want to know if the 2nd bit is on or off. Here is a way to do it:
int isAvailable (int bitString, int targetNum)
{
  return bit_string & (1 << targetNum);
}
  • bit_string: the bit string whose bits we are interested in. For example, 1101 and we are interested in the 2nd bit which is the bit in bold.
  • 1: is just our helper bit string. Its binary value is 0001
  • targetNum: is the position of the bit we're interested in. For example, targetNum is 2 if we're interested in the 2nd bit of 1101.
According to our example, to find out if the 2nd bit of 1101 is on or off, we'll just apply the formula like this: 1101 & (0001 << 2) = 1101 & 0100 = 0100 = 4. The result is 4 which is greater than 0, so we know that the bit we're interested in is on (1).
Let's do another example, if our bit string is 1001 and we're interested in the 1st bit which is 0 (in bold). Again, just apply the formula: 1001 & (0001 << 1) = 1001 & 0010 = 0000 = 0. The result is 0, so we know that our bit is off (0).
This trick concludes the first part of our series. Please stay tuned. Thanks for reading.

0 comments:

Post a Comment