Working with individual bits doesn’t just give you a way to pack lots of true or false values into a small space. This episode will show you how to isolate bits so you can work with them individually or in groups. Isolating bits like this is called masking.

The first thing to learn are the AND and OR truth tables. these tables list the output for each possible input combination. It is possible to consider AND and OR operations with more than two inputs but they need at least two inputs and that’s what these tables show.

AND Truth Table
0 AND 0 => 0
0 AND 1 => 0
1 AND 0 => 0
1 AND 1 => 1

OR Truth Table
0 AND 0 => 0
0 AND 1 => 1
1 AND 0 => 1
1 AND 1 => 1

If you think of the first input in these tables as your mask value, then you can see how whenever the mask value is 0 for AND operations, then it doesn’t matter what the other input is. The output will always be 0. And whenever the mask value is 1 for AND operations, then the output matches the second input.

For OR operations, the output matches the second value whenever the first mask value is 0. And whenever the mask value is 1, then the output will always be 1.

In the episode, I explain how to clear the most significant bit in a byte by using a mask. We need to perform an AND operation to clear one or more bits. If we have the binary value:
1100 1010 and we want to convert this to:
0100 1010 by clearing the bit on the left, then we need this mask:
0111 1111

The mask value in hexadecimal is then 7f.

And if we want to set the most significant bit again, then we need a different mask because this time, we will need to perform an OR operation. So continuing with this binary value:
0100 1010 and we want to convert to:
1100 1010 by setting the bit on the left, then we need this mask:
1000 0000

the mask value in hexadecimal is then 80.