Logical instructions have a multitude of uses in computer programs. They can be used to combine conditional expressions together (if this AND this but NOT this OR this, AND this, OR this, but not both, etc). They can be used to manipulate data in an almost arithmetic way. They can be used for combining bitmapped graphics together in simple ways. They can be used to obtain parts of a number, e.g. just the top 4 bits, or the middle 3 bits, etc.
There are four different types of logical operator that our machine implements. These are the logical NOT, OR, AND and XOR operators. Each of them operates on two 16 bit words of data, except for NOT, which operates on a single word.
The logical operators act bitwise. This means they act bit by bit. For example, the NOT operator takes each bit in the 16 bit word and flips it. If it was a 1, it becomes a 0; if it was a 0, it becomes a 1.
The other operators combine the bits from two different words. Each bit from the first word is combined logically with the corresponding bit in the second word, and the result is stored in the destination word. For example, the AND operator takes each bit of word one and the corresponding bit from word 2 and if both bits are 1's, the corresponding bit in the destination word is set to 1. In other words, the bit in the destination word is set to one, if and only if the bit in word one AND the bit in word two are both set.
The OR operator is similar to the AND operator except that the destination bit is set if and only if one OR the other of the two bits from the words being combined, are set.
The XOR operator is very much like the OR operator. The only difference is that instead of the destination being set if either or both of the bits are set, the destination bit is set to one if and only if one or the other bit is set, but not both.
Fortunately, performing logical operations in C is easy, since C itself provides logical operators. The C operator for AND is given by the symbol &. Thus if I want to AND two C variable (avar and bvar say) together, I simply type the expression avar & bvar. In all other respects, the logical operations act just like an addition or subtraction instruction, which we have already described. In other words, the way we access the memory and registers of our machine is the same. Only the actual operation (i.e. AND instead of addition) changes.
The C operator for OR is |. Again this is used in precisely the same way as an addition. The same goes for the C operator for XOR, which is ^. The final operator, NOT, is given in C by typing the tilde, ~. In other words, to obtain the logical NOT of a C variable (avar say), simply type ~avar.