Bit masking is a way to use the bits of a variable as on/off binary switches rather than have a separate variable for each switch.
Let's say you need a switch for Power (on/off) PaperLoaded (on/off) and TonerLow (on/off). You could three variables with values of 1 or 0. Or you could use three bits inside one variable instead since bit values are on/off.
If you are using C++ you should use the bitset<> template. Only in C should you be bitmasking.
Let's assume Power is bit 0, PaperLoaded is bit 1 and TonerLow is bit 2:
011
represents (right to left) Power is ON,PaperLoaded is ON and TonerLow is OFF.
Together these values are an integer 3.
To test for PaperLoaded ON you need to find the value of bit 1. You use a mask to do this:
010
The mask has an ON bit in the correct position, in this case bit 1.
Next, you AND this mask with yuor bits:
010
011
and the result is 010 since and AND produces a 1 only if both bits are 1.
So, 010 is your mask and 010 is your AND result. When these two are equal, bit 1 is ON. You have masked that bit.
The code for this uses 1 < 1. A 1 is 0000001 and a 1 shifted left by 1 is
00010:
- unsigned int switches = 0; //set all switches OFF
-
...some code.....
-
-
if (switches == 1<1)
-
{
-
//PaperLoaded ON
-
}
-
else
-
{
-
//PaperLoaded OFF
-
}
To set bit 1:
001 //assumes only Power is ON
010 //mask has the bit ON that you want to set ON in switches.
Now you OR the mask with the switches
001
010
011
In an OR the result is ON if either bit is ON. Here you assign the result to switches:
- switches = switches | 1<1;
To set a bit OFF, you AND the inverse of the mask and assign it to switches:
011
101 //is 010 with values reversed
001 //the AND result
- switches = switches & ~( 1 < 1);
Off you go. There is plenty of info in any book on C.