In digital electronics and software, we often meet the AND function. The logic symbols for an electronic AND gate are as follows:
The truth table for AND is as follows:
In words, the output is only a 1 when both inputs A and B are a 1. Some observations about this:
- If you AND a bit ‘A’ with a 1, then the result is A (preserved)
- If you AND a bit ‘A’ with a 0, then the result is always 0
We use these properties to reset or preserve individual or groups of bits
This is not limited to single bits. In software, we often perform logical operations on integers (binary numbers). Consider the following example:
The AND function is applied to each pair of bits. In the C or C++ programming language, this could be calculated as:
unsigned A = 170; //AA IN HEX A = A & 15;
The result is 10 //0A IN HEX
This is sometimes known as bit-masking. Where the mask has a 1, then a bit is preserved. Where the mask has a 0, then the bit is reset.