Logic Gates

Logic gates are the electrical equivalent of logical operators like AND in our programming languages. The most familiar are AND, OR, and NOT (&&, ||, and ! in many languages). There are others as well, some of which we'll get to later. If "logic gate" is offputting, it can always be read as synonymous with "logical operator" in this article: these are functions of two Boolean arguments, like && in a language like JavaScript.

We use truth tables to show the inputs and outputs of logic gates and logical operators. The table below describes the AND operator present in every programming language. For example, it shows that true AND false == false. To save space, we'll write 0 and 1 instead of false and true, but the meaning is the same for our purposes. (0 and 1 are also the convention in electrical engineering.)

x y x AND y
0 0 0
0 1 0
1 0 0
1 1 1

We can write our own implementation of AND without using any of the language's built-in logical operators. Here's a naive version in Python. All code examples here are shown as interactive REPL sessions, so Python statements are prefixed by >>> and ..., which aren't part of Python's syntax.

>>> def AND(x, y):
...     if x == 0 and y == 0: return 0
...     if x == 0 and y == 1: return 0
...     if x == 1 and y == 0: return 0
...     if x == 1 and y == 1: return 1

To write OR from scratch, we'd have to do the same thing, even though we already have AND. There's no way to write OR in terms of AND; or, likewise, to write AND in terms of OR. However, there are some universal gates, from which we can build any other gate. We'll get to those soon.

This is one section of The Programmer's Compendium's article on Digital Electronics, which contains more details and context.