About this book
Code: The Hidden Language of Computer Hardware and Software by Charles Petzold was published by Microsoft Press in 1999. A substantially revised second edition appeared in 2022, together with an interactive website on which readers can operate the book's circuits. The book is written for general readers. It assumes no knowledge of electronics, mathematics beyond simple arithmetic, or programming.
Its aim is to explain how a computer works by building one, in imagination, from the ground up. It starts with ideas so plain that a child could follow them: two friends who want to signal to each other across a street at night. It ends with processors, memory, operating systems, programming languages and graphical displays. At no point does it ask the reader to take a step on faith. Each new device is assembled from parts already explained.
The question the book answers is one most people who use computers never ask: what is actually happening inside the box. Popular explanations tend to stay at the level of metaphor, describing memory as a filing cabinet and the processor as a brain. Petzold refuses the metaphors. He wants the reader to see that a computer is made of a very large number of very simple switches, arranged with great cleverness, and that nothing mysterious happens anywhere along the way.
The title carries a double meaning. A code is a system of symbols that stands for something else, as Morse code stands for letters. Code is also what programmers write. The book connects the two senses. It shows that the programs we write are, at bottom, patterns of on and off in wires, and that the long road from a flashlight signal to a program is a road of codes built upon codes.
The book appeared at the end of the 1990s, when personal computers had become ordinary household objects and the internet was spreading fast, but when few users had any idea how their machines worked. It found a wide readership among programmers who had learned to code without learning hardware, among students, and among curious readers with no technical background. It has remained in print and in use ever since.
The second edition, published more than twenty years after the first, keeps the original's plan while rebuilding much of its middle. It constructs a complete processor in greater detail, showing the internal control circuits that the first edition described more briefly, and updates the closing chapters to reflect the internet, modern character encoding and the devices readers now use. Readers of either edition receive the same essential education; the second goes further into the machinery.
This study edition is a companion to that book. It explains what the book does, how its argument is built, what its key ideas are, how it relates to the other books in our foundations of computing bay, and how to read it with profit. It does not reproduce the book's text, its circuit diagrams, or its examples, and it is not a substitute for the patient step-by-step construction that is the book's real gift.
The author
Charles Petzold is an American programmer and writer, born in 1953. He studied mathematics and worked as a programmer in a large company before becoming a full-time technical writer in the mid-1980s. He wrote regularly for computer magazines, and in 1986 published one of the first magazine articles on programming the new Microsoft Windows environment.
His book Programming Windows, first published by Microsoft Press in 1988, became the standard guide for a generation of developers learning to write Windows applications. It went through several editions over the following decade and established his reputation for exact, patient explanation. In 1994 Microsoft recognised him as one of a small number of Windows pioneers for his part in helping developers adopt the platform. He later wrote books on the .NET programming frameworks and on newer Windows technologies.
Code stands apart from his programming books. It was a project of personal interest, aimed not at developers learning a particular system but at anyone who wanted to understand computers from first principles. It drew on his long experience of explaining difficult things to programmers, and on his own interest in the history of technology. Later he wrote The Annotated Turing, published in 2008, a line-by-line guide to Alan Turing's 1936 paper on computable numbers, which shares the same conviction that foundational ideas can be made accessible to non-specialists willing to work through them carefully.
Knowing the author's background helps a reader understand the book's character. Petzold is not an electrical engineer, and he does not write like one. He writes like a programmer who went back and taught himself what lies under the software, and who wants to save his reader the confusion he met on the way. That gives the book its tone: practical, patient, curious and never condescending.
The shape of the argument
The book is organised as a long climb from the simple to the complex. Its early part is about codes and signals: ways of representing letters, numbers and messages with a small set of symbols. It looks at systems people actually used, such as the dots and dashes of telegraphy and the raised dots of writing for the blind, and draws out the principles they share.
Its next part is about electricity and switches. It explains, without equations, what a circuit is and how a switch controls it. It then introduces the relay, a switch operated by electricity rather than by hand, which was the key component of the nineteenth-century telegraph network. With relays in hand, the reader can build circuits in which one signal controls another.
A parallel strand develops numbers. The book examines why we count in tens, how counting would work with other numbers of fingers, and finally how counting works with only two digits. Binary numbers then meet relay circuits, and the two strands join: wires that are either on or off can represent binary digits, and switches can be arranged to compute with them.
The middle of the book is the construction. From relays come logic gates; from gates come circuits that add; from feedback come circuits that remember; from many memory circuits comes an addressable memory; from memory, an adder and a clock comes a machine that follows a list of instructions. Each step is small. Taken together they amount to a working computer, at least on paper.
The last part of the book climbs above the hardware. It explains how real microprocessors are organised, how text is encoded, how components communicate over shared wires, what an operating system does, how fractional numbers are stored, how programming languages relate to machine instructions, and how graphical displays work. These chapters move faster and cover more ground; the reader is now trusted to fill in details by analogy with what has gone before.
The second edition changes the construction substantially. It builds its processor in more detail, showing more of the internal control logic that the first edition summarised, and it updates the later chapters on software and the internet. The overall arc remains the same: from signals between friends to a programmable machine, and then upward through the layers of software.
Throughout, the method is cumulative. Nothing is used before it is built. A reader who has followed each step can, at the end, trace any operation of the computer down through the layers to individual switches opening and closing. That is the book's promise, and it keeps it.
Idea one: a code is an agreement
The book begins with the simplest possible question: how two people can communicate when they cannot speak. The answer leads to the idea of a code: an agreed correspondence between symbols and meanings. A code is not a property of the symbols. A flash of light means nothing by itself. It means a letter only because both sides have agreed that it does.
Morse code shows how a very small set of symbols can carry any message. With only short and long signals, and pauses between them, it encodes every letter, digit and common punctuation mark. Its designers gave short codes to frequent letters, so that common messages are quick to send. This is an early instance of an idea that runs through all of computing: the cost of a representation should match how often it is used.
Braille shows a different design. Each character occupies a fixed cell of six positions, each of which is raised or flat. That gives a fixed number of possible patterns, which must be shared among letters, digits, punctuation and special signs. Braille solves the shortage by using some patterns as shift signals that change the meaning of what follows. Modern character encodings face exactly this problem and use exactly this trick.
An everyday example of our own: a household where a lamp in the window means come home for dinner. The lamp carries one bit of agreed information, on or off. Add a second lamp and the household can signal four different things. Each added lamp doubles the number of possible messages. This doubling is the arithmetic heart of every code built from binary choices.
The idea is often confused with secrecy. In ordinary speech a code is something hidden, a cipher. Petzold's sense is broader and more basic: any systematic way of representing information. Secrecy is a special use of codes, not their essence. The computer is a code machine in the broad sense: everything inside it, numbers, letters, images, instructions, is represented by agreed patterns of on and off.
Idea two: number is independent of its notation
We count in tens because we have ten fingers. The book makes this point vividly and then asks the reader to imagine creatures with eight fingers, or four, or two. Each would develop a number system with a different base, and each would work perfectly well. The quantities would be the same; only the written forms would differ.
This is a deeper point than it seems. A number is not the same as the string of digits that names it. Thirteen apples are thirteen apples whether we write the quantity in decimal, in octal, or in binary. Positional notation, the system in which a digit's value depends on its place, works the same way in any base: each place is worth the base times the place to its right. Once this is understood for base ten, it can be understood for any base.
Binary, base two, has only two digits, zero and one. It looks clumsy to humans because its numerals are long. Ten in decimal becomes four digits in binary. But binary has one overwhelming advantage for machines: each digit has only two possible values, which can be represented by anything with two states, a switch on or off, a voltage high or low, a hole punched or not. A device that has only to distinguish two states can be made simple, cheap and very reliable.
The book introduces the word bit, short for binary digit, and shows that a bit is the smallest unit of information: the answer to one yes-or-no question. Groups of bits can represent anything that can be enumerated. Eight bits together, a byte, can take two hundred and fifty-six distinct values, enough for all the letters, digits and punctuation of English with room to spare. Hexadecimal notation, base sixteen, is introduced as a convenient shorthand that groups bits four at a time, which is why programmers use it.
A common confusion is to think that computers use binary because binary is somehow more fundamental or natural. It is not more fundamental as mathematics. It is more convenient as engineering. Early computers were built using decimal and other systems, and some worked well. Binary won because two-state devices are easier to build reliably, and because binary arithmetic and logic turn out to be the same thing, as the next idea shows.
There is also a practical lesson in this chapter for anyone who works with numbers. Converting a number between bases by hand, a few times, removes the mystery from the long strings of zeros and ones and from the hexadecimal values that appear in error messages and memory listings. It also clarifies how many distinct values a field of a given width can hold, a question that matters whenever data is stored, from dates to prices to identifiers. Many software failures have come from a field that was a few bits too narrow for the values it later had to hold.
Idea three: switches can do logic
The book's most important conceptual step is to join two ideas that seem unrelated: the logic of true and false, and the behaviour of electrical switches. In the 1850s George Boole showed that reasoning with statements that are either true or false could be treated as a kind of algebra, with operations such as and, or and not. In 1937 Claude Shannon, then a graduate student at MIT, showed in his master's thesis that circuits of switches obey exactly this algebra. Two switches in series let current flow only if both are closed, which is and. Two switches in parallel let current flow if either is closed, which is or.
Petzold leads the reader to this connection slowly and concretely. He starts from an everyday choice that must satisfy several conditions at once, writes the conditions in Boole's terms, and then shows how they can be wired as switches in series and parallel. By the time Boole's algebra is named, the reader has already been using it.
The relay makes the connection powerful. A relay is a switch closed by an electromagnet. When current flows through the magnet's coil, it pulls a metal arm and closes a second circuit. So the output of one circuit can operate a switch in another. This means that logical operations can be chained: the result of one and can become an input to an or. With relays, one can build logic gates, standard circuits that compute and, or, not and their combinations, and connect them in any arrangement.
A useful analogy is plumbing with valves that are themselves opened by water pressure. Water in one pipe opens a valve in another, which lets water into a third. With enough pipes and valves of this kind, one can build a machine whose outflow depends in any desired way on its inflows. Logic gates are such valves for electricity.
The idea is often misunderstood as a claim that computers think logically in the human sense. They do not. They implement Boolean functions, mappings from patterns of on and off to other patterns of on and off. That such mappings can represent arithmetic, text processing and much else is remarkable, but it is not reasoning. The book is careful to keep the mechanism visible so that this confusion does not arise.
Relays have long since been replaced by vacuum tubes and then by transistors, which perform the same switching action millions of times faster and smaller. The book explains this succession briefly. The logic is the same in every technology; only the speed and size change. That is one of the reasons Petzold uses relays: they are slow and visible, so the reader can imagine every click.
Idea four: arithmetic is logic
Once gates exist, the book shows that binary addition can be done with them. Adding two single bits produces a sum bit and a carry bit. The sum is one when exactly one of the inputs is one, which is a gate called exclusive or. The carry is one when both inputs are one, which is a plain and gate. A circuit that does this is called a half adder.
To add numbers of many bits, each column must also take into account the carry from the column to its right. A full adder handles three inputs, two bits and an incoming carry, and can be built from two half adders and an or gate. Chain eight full adders together, passing each carry to the next, and the result adds two eight-bit numbers. The book builds this adding machine step by step, so that the reader sees exactly how a flick of input switches produces a lit pattern of output lamps that is the correct sum.
Subtraction comes next, and with it the problem of negative numbers. The book shows how the method called two's complement lets the same adding circuit perform subtraction, by representing a negative number as a particular pattern of bits that behaves correctly under addition. The trick resembles the way an odometer, rolled back past zero, shows a very large number: in a fixed number of digits, going below zero wraps around to the top. With the right interpretation, the wrapped number acts as a negative.
The importance of this idea is hard to overstate. It shows that arithmetic, which seems to be about quantities, can be performed entirely by logic, which seems to be about truth and falsehood. In binary, they are the same thing. This identity is what makes a computer possible: a single kind of component, the switch, suffices for both calculation and decision.
It is often thought that computers contain some special arithmetic part distinct from their logic. In a sense they do, since processors have arithmetic units, but those units are made of the same gates as everything else. There is no separate substance of number inside the machine. There are only switches arranged in patterns that, when interpreted, behave like numbers.
Idea five: feedback makes memory
An adding machine forgets. Its output depends only on its present inputs, and when the inputs change, the old answer is gone. A computer must remember: the numbers it is working on, the instructions it is following, its place in the list. The book shows how memory arises from a surprising source, a circuit whose output is fed back into its own input.
The simplest example is a relay wired so that it switches itself off as soon as it switches on, and on again as soon as it switches off. It buzzes back and forth forever. This oscillator, once tamed, becomes the clock that paces the computer, producing a steady beat to which everything else keeps time.
A different arrangement of feedback produces a circuit with two stable states. Once pushed into one state, it stays there until pushed into the other. This is a flip-flop, and it remembers one bit. The book builds several kinds, including one that captures the value on a data input at the moment a clock signal arrives and holds it until the next. Such a circuit is a latch: it records a value on command and keeps it. Eight latches side by side hold a byte.
The clock deserves a further word. Circuits made of gates take a little time to settle after their inputs change, because each switch takes time to act. If the next step began before the previous one had settled, the machine would read half-finished results. The clock solves this by dividing time into equal steps, long enough for every circuit to settle, and by letting flip-flops capture new values only at the edge of each beat. Everything in the machine then moves in step, like rowers following a drum. The speed of the clock, measured in beats per second, sets how many steps the machine can take, which is why clock rates came to be quoted as a measure of computer speed.
An analogy: a light switch on a wall remembers whether you last turned it on or off, because its mechanism has two stable positions. A doorbell button does not, because it springs back. A flip-flop is an electrical light switch that can be flipped by another circuit. Its memory is simply its tendency to stay where it was put.
With flip-flops the book can also build counters, circuits that step through binary numbers one at a time with each clock pulse. A counter combined with a clock is the beginning of sequence, of doing one thing after another. That is the step from a calculator, which does one thing when asked, toward a computer, which does many things in order.
The idea is often confused with the notion that memory must be a stored physical record, like marks on paper. Flip-flop memory is not a mark. It is an active state, maintained by current flowing in a loop. Turn off the power and it vanishes. This is why the working memory of a computer is lost when it is switched off, and why other technologies, such as magnetic disks and flash memory, are needed for storage that lasts.
Idea six: addresses turn many memories into one
A single flip-flop stores one bit. A useful memory must store thousands or millions. The problem is not making many flip-flops, which is just repetition, but selecting among them. The book solves it with addresses.
Each storage location is given a number, its address. To write to a location, the computer puts the address on a set of wires, puts the data on another set, and signals a write. A circuit called a decoder takes the address and activates exactly one location, which captures the data. To read, the computer puts the address on the wires and a selector circuit routes the contents of that one location to the output. The book builds decoders and selectors from gates, so the reader sees how a pattern of bits on address wires picks out one location among many.
A concrete image: a building with numbered post boxes. To deliver a letter, you need the box number and the letter. To collect one, you need only the number. The number of boxes you can address depends on how many digits the numbers have. With ten address wires you can select among a little over a thousand locations; with twenty, among about a million. Each added wire doubles the reach, the same doubling met in the first idea.
This organisation is called random-access memory, because any location can be reached as quickly as any other, unlike a tape, which must be wound to the right place. Random access is what lets a computer jump to any instruction or any piece of data in a single step. The book shows that it is built entirely from the same flip-flops and gates as everything else.
The book also distinguishes memory that can be written from memory that can only be read. Read-only memory holds fixed contents, such as the first instructions a computer runs when it is switched on, and keeps them without power. Writable memory holds the changing data of a running program and loses it when power is lost. Both are addressed in the same way. The difference lies in how each location holds its value.
The idea is commonly confused with the notion that memory contains things in the way a drawer contains objects. Memory contains patterns, and a pattern means nothing until something interprets it. The same byte at the same address might be a number, a letter, part of a picture, or an instruction. What it is depends on how the rest of the machine uses it. This becomes crucial in the next idea.
Idea seven: the stored program
The book now has an adder, memory and a clock. The decisive step is to automate them. Petzold constructs a machine that, guided by a counter, steps through memory locations, takes numbers from them and adds them into a running total held in a special register called an accumulator. At first the sequence of operations is fixed by the wiring. Then he adds a second memory, or a part of the same memory, that holds codes saying what to do at each step: load a number, add it, store the result, stop.
Those codes are instructions, and the machine that reads and executes them is a processor in miniature. The essential move is that the instructions are stored in memory as numbers, just like the data. This is the stored-program idea, associated with the design reports written by John von Neumann and his colleagues in the 1940s. A machine built this way can be made to do entirely different tasks by changing what is in memory, without changing any wires.
Once instructions live in memory, new powers appear. A jump instruction tells the machine to continue from a different address instead of the next one. A conditional jump does so only if some condition holds, such as a result being zero. With conditional jumps a program can make decisions and repeat steps, and the machine becomes capable of general computation. The book shows how a simple loop, such as multiplying two numbers by repeated addition, can be written in such codes and run.
The book also shows the cost of this generality. Writing a program as a list of numeric codes is tedious and error-prone, and a single wrong number can send the machine jumping to a meaningless address. The reader who has written even a few instructions by hand understands at once why assemblers, and later high-level languages, were invented. The motive for every layer of software above the hardware is visible from this first, painful layer.
An analogy is a player piano. The piano does not change, but a different paper roll makes it play a different tune. A stored-program computer is a piano that can also read instructions from its roll telling it to skip ahead or go back depending on what it has played so far, and to punch new holes in its own roll. That last ability, to treat instructions as data, is what gives software its power and its dangers.
This idea is often confused with mere automation. Many machines before computers were automatic: looms controlled by punched cards, music boxes, mechanical calculators. What distinguishes the stored-program computer is generality. Because instructions and data share one memory, and because the machine can branch on conditions, it can in principle compute anything that can be computed, limited only by memory and time. That generality connects Petzold's homely construction to the theory of computation explored elsewhere in this bay.
From relays to chips
Between the relay circuits of the middle chapters and the microprocessors of the later ones lies a story of components, which the book tells briefly but clearly. The logic never changes. What changes is the device that does the switching, and with it the speed, size, cost and reliability of the machine.
Relays were used in some of the earliest automatic calculators of the late 1930s and 1940s. They were reliable enough but slow, since a metal arm must physically move, and they wore out. Vacuum tubes, which control a current electrically with no moving parts, were thousands of times faster and powered the first large electronic computers of the 1940s. But tubes were large, hot and prone to burn out, and a machine with thousands of them spent much of its life being repaired.
The transistor, invented at Bell Laboratories in 1947, did the same switching job in a small piece of solid material. It was faster, smaller, cooler and far more reliable. In the late 1950s Jack Kilby and Robert Noyce independently showed how to make many transistors and their connections together on a single piece of semiconductor, the integrated circuit. From that point the number of transistors that could be placed on a chip grew steadily, roughly doubling at regular intervals, a trend Gordon Moore noted in 1965 and which became known as Moore's law.
By the early 1970s it was possible to put an entire processor on one chip, the microprocessor. This made computers cheap enough for individuals to own, and within a decade personal computers had arrived. The book connects this history to the construction the reader has just completed: the processor on a modern chip is the same kind of machine as the one built from relays in the preceding chapters, made of switches millions of times smaller and faster.
An analogy helps to hold the point. A sentence can be written with a chisel on stone, with a pen on paper, or with light on a screen. The sentence is the same; only the medium changes, and with it the speed and cost of writing. Logic circuits are like sentences, and relays, tubes and transistors are like stone, paper and screen. Petzold uses relays because they are the easiest medium to see, not because they matter today.
A common misunderstanding is that computers became possible only with modern electronics. In principle, a computer can be built from anything that can switch: relays, tubes, transistors, even water valves or mechanical rods. Babbage designed one with gears. What electronics provided was speed and scale, which made computers practical rather than merely possible. The book's method makes this distinction unusually vivid.
Idea eight: real processors and the instruction set
Having built a toy processor, the book turns to real ones. The first edition examines two influential microprocessors of the mid-1970s, the Intel 8080 and the Motorola 6800, which powered early personal computers. It explains their registers, their instruction sets, how they address memory, and how they use a stack to remember where to return after calling a subroutine. The second edition builds its own processor modelled closely on the Intel 8080, constructing much of its control logic in detail.
The reader learns that a real processor has the same essential parts as the toy: registers to hold values, an arithmetic and logic unit made of gates, control logic that decodes each instruction and sets the switches accordingly, and a program counter that tracks the address of the next instruction. The differences are of scale and refinement: more registers, more instructions, more ways to address memory, and much greater speed.
The book also introduces assembly language, a way of writing instructions as short words instead of numbers. An assembler translates these words into the numeric codes the processor reads. Assembly is the first layer of software above the hardware, and seeing it emerge directly from the instruction codes makes clear that it is only a more readable way to write the same patterns of bits.
The idea is sometimes misunderstood as historical curiosity, since modern processors are vastly more complex than chips from the 1970s. But the essentials have not changed. Every modern processor still fetches instructions from memory, decodes them, performs operations on registers, and moves data to and from memory. The extra complexity of modern chips, such as pipelining and caches, makes the same operations faster without altering what they are. Hennessy and Patterson's Computer Architecture, in this same bay, takes up the story there.
Idea nine: text is numbers by agreement
A computer stores only numbers, yet it displays words. The book returns to its opening theme, codes, to explain how. Each character is given a number by agreement, and text is stored as a sequence of such numbers. The book discusses ASCII, the American Standard Code for Information Interchange, a seven-bit code from the 1960s that assigns numbers to the English letters, digits, punctuation and a set of control characters.
The book shows that the choices in ASCII were made with care. The digits occupy a block whose low bits equal their values, so converting a character to a number is simple. Upper-case and lower-case letters differ by a single bit, so changing case is a single operation. Control characters, such as those for a new line or a tab, descend from the commands that once operated teleprinters. Each design decision makes some common task cheap, echoing the frequency principle met in Morse code.
ASCII serves English and not much else. The book explains the problem this created for other languages and how it was addressed, first by many incompatible extended codes and then by Unicode, a single system intended to cover every writing system in the world. Indian scripts such as Devanagari, for example, are represented in Unicode, which is why a modern computer can display them alongside Latin and other scripts. The second edition gives more attention to Unicode and its encodings than the first.
This idea is often taken for granted until something goes wrong, such as a document that displays as meaningless symbols because it was read with the wrong encoding. That failure reveals the truth the book has been making plain: the bytes do not know what they mean. Meaning comes from the agreement between the writer and the reader, which is exactly where the book began, with two friends agreeing on what a flash of light should signify.
Idea ten: layers of software
The final chapters climb through the layers that make a bare processor into a usable computer. The book describes how the parts of a computer are connected by a bus, a shared set of wires that carries addresses, data and control signals between the processor, memory and devices such as keyboards and displays. It explains how devices signal the processor, and how the processor talks to them.
It then describes the operating system, the program that runs first when the computer starts and manages everything else: loading other programs, organising files on disk, handling input and output. The book shows that an operating system is itself just a program, made of the same instructions as any other, but given the special job of providing services that other programs share.
It explains how fractional numbers are represented, with a fixed or floating binary point, and why floating-point arithmetic introduces small rounding errors that surprise many programmers. It explains how high-level programming languages are translated into machine instructions by compilers, so that a programmer can write a short formula and have it turned into a sequence of loads, arithmetic operations and stores. And it explains how graphical displays work, representing images as arrays of numbers, one for each dot on the screen.
Floating point is a good example of how a hidden layer surfaces. A fraction such as one tenth has an exact, short form in decimal but an endless repeating form in binary, much as one third is endless in decimal. A computer must cut the binary form off after a fixed number of bits, so the stored value is very slightly different from one tenth. Add ten such values together and the total may not be exactly one. The book's explanation of floating-point representation makes this behaviour, which puzzles many programmers, entirely predictable.
Each layer hides the one beneath it. A user of a word processor need not know about the operating system; a programmer in a high-level language need not know about registers; a logic designer need not know about the physics of transistors. This hiding is called abstraction, and it is what makes complex systems possible to build and use. But hiding is not the same as absence. The book's whole purpose is to lift each layer in turn and show what lies beneath, so that the reader understands that the layers are made, not given.
An analogy: a city. A visitor uses streets and buildings without thinking about the pipes, cables and foundations. The city works because those lower layers are reliable and out of sight. But someone who knows what lies beneath, where the water comes from and where the wires run, understands the city in a way the visitor does not, and can repair it or improve it when something fails.
Idea eleven: what hidden means
The subtitle speaks of a hidden language, and it is worth asking in what sense the language of the computer is hidden. It is not secret. Every detail of how gates, memory and processors work is published and taught. It is hidden in the way the foundations of a house are hidden: covered over by the layers built on them, so that users rarely see or think about them.
This hiding is deliberate and useful. It is what allows a person to write a letter without knowing about flip-flops, and a programmer to write a program without knowing about transistors. Each layer offers the one above a simpler, more convenient picture of the machine, and keeps its own complications to itself. Engineers call this abstraction, and the history of computing can be told as the history of building better abstractions.
But hiding has a cost. When something goes wrong, or when performance matters, the hidden layers come back into view. A program runs slowly because of the way memory is organised. A calculation gives a slightly wrong answer because of how fractional numbers are stored in binary. Text turns into nonsense because two programs disagree about an encoding. People who know only the top layer are helpless in these moments. People who know what lies beneath can reason their way to the cause.
The book's quiet argument is that everyone who works with computers benefits from knowing, at least once, what is under the surface. Not in order to work at the lowest level every day, but in order to stop treating the machine as magic. Once a reader has seen that a computer is switches all the way down, it becomes an object to be understood rather than a power to be obeyed. That change of attitude may be the book's most lasting gift.
This idea is easily confused with nostalgia for low-level programming, or with the claim that every programmer should write assembly language. Petzold makes no such claim. He values the layers and explains why they exist. His point is only that understanding the layers, as opposed to living inside one of them, is within reach of anyone patient enough to climb down and back up.
Following one keystroke down
A good way to test one's understanding of the book is to follow a single ordinary event through all its layers. Take the act of pressing a key on a keyboard and seeing a letter appear on the screen. This walk is our own, not the book's, but it uses only ideas the book provides.
Pressing the key closes a switch. A small circuit in the keyboard notices which switch changed and sends a number identifying the key along a wire, as a sequence of bits. That is a code in the book's opening sense: an agreed number for each key.
The number arrives at the computer and a device controller signals the processor that input is waiting. The processor, which has been fetching and executing instructions in a loop, saves its place and jumps to a part of the operating system written to handle the keyboard. Those instructions read the number from the device, translate it into a character code, perhaps the Unicode value for the letter, and place it in memory where the running program can find it.
The word processor, a program in memory like any other, retrieves the character and adds it to the document it holds in memory, as a number in a sequence of numbers. It then asks the operating system to update the display. Somewhere a program looks up the shape of the letter in a font, a description of each character's outline, and sets the corresponding dots in an array of numbers that represents the screen. A display circuit reads that array many times a second and lights the screen accordingly.
At every step, the work is done by a processor fetching instructions from addressed memory, decoding them, and setting gates so that adders and selectors move and combine bits. Each instruction is a pattern of bits. Each bit is held in a flip-flop or a similar circuit. Each gate is a handful of switches. The press of a key has set off millions of switch changes, all following the logic Boole described and Shannon wired.
A reader who can tell this story, at whatever level of detail, has absorbed the book. A reader who cannot should return to the chapter where the chain breaks. The exercise also shows why the book's layered method matters. No one can hold the whole story in mind at the level of switches. One understands it by knowing each layer well enough to trust it, and then reasoning about the layer above.
The tradition around it
Code belongs to a long tradition of explaining machines by building them up from simple parts. Charles Babbage, whose Passages from the Life of a Philosopher sits in this bay, described his own engines in terms of gears and levers that a reader could picture. In the twentieth century, popular books on how computers work were common, but most stayed at the level of block diagrams and metaphors. Petzold's distinction was to go all the way down, to individual switches, without losing a general reader.
Several books in this bay sit directly beneath or beside it. The Mathematical Theory of Communication by Shannon and Weaver provides the theory of the bit that Code uses informally. Shannon is the same man whose master's thesis linked switches to Boolean logic, a link Code depends on. The Computer and the Brain by John von Neumann reflects on the stored-program machine whose design Code reconstructs, and Turing's Cathedral by George Dyson tells the story of how that machine was built at Princeton.
Above Code, in the sense of assuming its material, sit several other books in the bay. Computer Architecture: A Quantitative Approach by Hennessy and Patterson shows how professional designers make processors fast. The C Programming Language by Kernighan and Ritchie teaches a language that stays close to the machine Code describes, with its pointers mapping directly to addresses in memory. Compilers: Principles, Techniques, and Tools by Aho, Sethi and Ullman explains in depth the translation from high-level language to machine instructions that Code sketches.
In a different direction, the theory books in the bay explain what the machine Code builds is capable of in principle. Introduction to the Theory of Computation by Sipser shows that a machine like the one Code constructs, given enough memory, can compute anything that any computer can, and also that some problems lie beyond every computer. Gödel, Escher, Bach by Hofstadter explores the strange loops that arise when a system can represent and manipulate its own descriptions, the very property the stored program gives a computer.
Later popular books on how computers work have often followed Code's lead, and courses that have students build a computer from logic gates up to a working system follow the same bottom-up path. The second edition's interactive website, which lets readers operate the circuits, extends the book's method into a medium it could only describe in 1999.
Questions and criticisms
The most common criticism is about pace. The early chapters move slowly, sometimes very slowly, through ideas such as counting in other bases that some readers already know. The later chapters move quickly, covering operating systems, languages and graphics in a few pages each. Readers with some background may find the start tedious; readers without it may find the end rushed. This unevenness is partly deliberate, since the foundations need the most care, but it is real.
A second criticism concerns the first edition's choice of example processors. The Intel 8080 and Motorola 6800 were already old in 1999, and their details, such as particular instruction codes, are not what a modern reader needs. Petzold's reason was that these simple chips are easier to understand than modern ones. The second edition addresses the concern by building its own processor in more detail and updating the later material, but readers of the first edition should treat its chip descriptions as illustrations rather than current practice.
A third point is that the book stops short of modern performance techniques. It does not explain pipelines, caches, multiple cores or graphics processors in any depth. Its machine is correct but slow. This is a fair limit for a book of its purpose, and other books in the bay fill the gap, but a reader should not mistake Code's simple processor for a picture of how a modern chip achieves its speed.
Some readers find the mix of history and construction distracting, wishing either for a pure technical account or a pure history. Others value the mix, since the history explains why things are the way they are. The criticism is a matter of taste.
What has held up is nearly everything that matters. The logic of switches, the arithmetic of gates, the nature of memory, the stored-program principle and the layered structure of software are as true now as when the book was written. They will remain true as long as computers are built from switches. Few books about computers age so well, because few go so deep.
What the book asks of its reader
Code is often described as easy, and in one sense it is: it requires no background. In another sense it asks a good deal. It asks the reader to follow long chains of small steps without losing the thread, to hold several circuits in mind at once, and to accept that understanding comes from tracing details rather than from grasping a single big idea. Readers who skim it come away with a vague impression that computers are made of switches. Readers who work through it come away able to explain how.
It also asks for a certain kind of trust. Early chapters spend time on matters, such as other number bases or the structure of Braille, whose purpose is not immediately clear. The purpose appears later. A reader who trusts the author through these chapters is rewarded, because each piece returns at its proper moment. This is a feature of all well-built cumulative explanations, in mathematics as in engineering, and Code is a good place to learn to read them.
Finally, it asks for a willingness to be surprised by simplicity. Many readers expect that a computer must contain something more than switches, some special ingredient that accounts for its power. The book's long demonstration that there is no such ingredient can be unsettling. The power comes entirely from arrangement, from the way simple parts are connected and layered. Accepting this is part of what the book teaches.
Why it is on this shelf
This shelf gathers books on Vedanta, Jyotish, science, economics and technology for a reader who wants to understand things from their foundations. Code is on it because it gives exactly that understanding of the machine that now mediates so much of modern life. After reading it, a computer is no longer a sealed box. It is an arrangement of simple parts, each of which the reader has seen built.
It is also the best entry point to this bay. The other books on computing assume, in different ways, that the reader knows what a bit is, how a gate works and what a processor does. Code supplies that knowledge with no prerequisites. A reader who starts here will find the rest of the bay much more accessible.
There is a further reason that bears on the shelf as a whole. The book is a long demonstration that great complexity can arise from very simple elements arranged in layers, each layer creating something the layer beneath does not contain on its own. A switch knows nothing of numbers; an adder knows nothing of programs; a processor knows nothing of words. Yet the whole does all these things. Readers of philosophy, of systems in nature, and of economies will recognise the pattern and find in Code an unusually clear and concrete instance of it.
How to read it
Read the book in order. Unlike most books in this bay, it truly depends on sequence; each chapter uses what the previous ones built. Do not skip the early chapters on codes and number systems even if they seem easy. They set up vocabulary and habits that the later chapters rely on.
Read with a pencil and paper. When the book introduces a circuit, draw it yourself before reading on, and trace a few inputs through it by hand: mark which wires are on, which relays are closed, and what the output is. For the adder, add two small binary numbers by hand and then trace the same addition through the circuit. For the flip-flop, follow the feedback loop through a change of input. This is slow, and it is where the understanding comes from.
If you have the second edition, use its companion website to operate the circuits interactively after you have traced them on paper. Seeing them work confirms what you have worked out.
The heart of the book is the middle: logic gates, the adding machine, subtraction, flip-flops, memory and the construction of the programmable machine. Give these chapters the most time, perhaps a week each if reading in the evenings. The final chapters on operating systems, languages and graphics can be read more quickly on a first pass; they are surveys rather than constructions, and they will make more sense after you have read other books in the bay.
A reasonable pace is two or three chapters a week, with the middle chapters slower. The whole book can be read carefully in two or three months.
Keep a small notebook of the circuits as you build them, one page each, with a sketch, a sentence on what it does and a note on which earlier circuits it uses. By the end the notebook is a map of the whole machine, and reviewing it in order is the quickest way to recall the book's argument months later.
From this shelf, read Kernighan and Ritchie's The C Programming Language next, to program in a language close to the machine you now understand. Then read Hennessy and Patterson's Computer Architecture for how real processors are made fast, and Sipser's Introduction to the Theory of Computation for what such machines can and cannot do in principle. For history, read Dyson's Turing's Cathedral and Hodges's Alan Turing: The Enigma.
Questions to carry
- What makes a pattern of symbols into a code, and where does its meaning come from?
- Why does adding one more binary choice double the number of possible messages?
- Why did computers come to use binary rather than decimal, and was that choice inevitable?
- How can the same circuit be described both as logic and as arithmetic?
- How does a negative number exist in a machine that only has on and off?
- What is the difference between a circuit that computes and a circuit that remembers?
- Why is working memory lost when the power goes off, and what must be done to keep information?
- How does a pattern of bits on a set of wires select one location among millions?
- What changes when instructions are stored in the same memory as data?
- Why does a conditional jump turn a calculator into a general computer?
- When the same byte can be a number, a letter or an instruction, what decides which it is?
- What is gained and what is lost when each layer of a system hides the layers beneath?
- Which parts of a modern computer would you still be unable to explain after this book, and where would you look next?
Words to know
- Code: An agreed system of symbols that represents information, such as letters or numbers.
- Bit: A binary digit, zero or one; the smallest unit of information, the answer to one yes-or-no question.
- Byte: A group of eight bits, able to represent 256 distinct values.
- Binary: The number system with base two, using only the digits zero and one.
- Hexadecimal: The number system with base sixteen, used as shorthand for groups of four bits.
- Relay: A switch operated by an electromagnet, so that one circuit can control another.
- Transistor: A tiny electronic switch with no moving parts that replaced relays and vacuum tubes.
- Boolean algebra: The algebra of true and false values with operations such as and, or and not, introduced by George Boole.
- Logic gate: A circuit that computes a Boolean function of its inputs, such as and, or, not or exclusive or.
- Half adder: A circuit that adds two bits, producing a sum and a carry.
- Full adder: A circuit that adds two bits and an incoming carry; chained together, full adders add numbers of many bits.
- Two's complement: A way of representing negative numbers in binary so that the same circuit can add and subtract.
- Oscillator: A circuit that switches back and forth on its own, used as a clock.
- Flip-flop: A circuit with two stable states, made by feedback, that stores one bit.
- Latch: A flip-flop that captures and holds the value on its data input when signalled.
- Address: The number that identifies one location in memory.
- Decoder: A circuit that activates exactly one of many outputs according to a binary input, used to select memory locations.
- Random-access memory: Memory in which any location can be read or written directly by its address in the same time.
- Accumulator: A register that holds a running result of arithmetic operations.
- Stored program: The principle that instructions are held in memory as numbers, alongside data.
- Conditional jump: An instruction that continues from a different address only if some condition holds.
- Assembly language: A readable form of machine instructions using short words, translated into numeric codes by an assembler.
- ASCII: A seven-bit character code assigning numbers to English letters, digits, punctuation and control characters.
- Unicode: A universal character encoding system intended to cover all the world's writing systems.
- Operating system: The program that manages a computer's resources and provides services to other programs.
A note on this edition
This is a study edition written for this shelf in our own words. It describes and explains Code: The Hidden Language of Computer Hardware and Software by Charles Petzold, but it does not reproduce the book's text, its circuit diagrams or its examples. The book itself is in copyright, in both its first and second editions; it is worth getting from a library or bookshop and reading slowly, drawing the circuits as you go. Any errors in this companion are ours, not the author's.