This tutorial guide details the main Boolean Logic operators, and gives some useful information about how they can be used in bitwise operations. We shall also cover uses for bitwise operations and Boolean Logic in programming. The reader should be familiar with:
Boolean Logic is based around the evaluation of binary values. Examples of binary values are:
Any decision making machine will essentially boil down the vast majority of conditions to a binary evaluation. In programming we talk about operators that take two inputs and return a single output. This is modeled on the first binary computing systems called logic gates, of which only one (the AND gate) is required in order to build every other kind of decision making mechanism. At the heart of modern electronics are many millions of such gates, of which there are four distinct types that have been implemented in programming languages:
With these four logical operators, we can build complex comparison statements, and manipulate data using bitwise operations in which each bit in a given byte is evaluated with reference to the equivalent bit in a second byte, using logical operations, to yield the result. The key is in understanding the logical operators, or gates.
A quick note : although we are using the term gates and operators interchangeably, any electronic engineer will know that the presentation of the four operators here does not actually represent the equivalent in electronic terms. The oversimplification is due to the fact that only these four are typically implemented in programming.
The simplest of the logic operators is the AND gate:
"The output is True if both inputs are true."
This can be represented by the table:
The OR gate can be expressed as:
"The output is True if one of the inputs are true."
This can be represented by the table:
Note that if both inputs are true, then the condition stated above is satisfied.
An XOR gate has the following table:
The full name for this is the eXclusive OR gate:
"The output is True if exactly one of the inputs are true."
This is a simple inversion operator:
"The output is False if the input is True, and True if the input is False."
Given that a byte comprises 8 bits, arranged in such a fashion that a number between 0 and 255 can be represented (or -127 to +127 signed), we can apply these tables to individual bits in a byte. This is known as a bitwise operation. For example, supposing we had two numbers : 42 and 224. These would be represented as:
If we wished, we could combine these by way of an XOR (sometimes known as a masking) operation:
The result is that, everywhere that there are two corresponding bits in the bytes set to 1, the corresponding output bit is also set to 1. So, 42 XOR 224 is 202. We can do the same for AND and OR:
Putting a NOT gate behind the output inverses the above results, and is left as an exercise for the reader.