Computer Fundamentals and Introduction to Programming · Lecture Notes

Chapter 1.3: Computers

A computer is built from billions of tiny switches that can tell only two states apart. Yet the same machine calculates, writes text, shows pictures, and plays music. These notes explain how that gap is bridged. First they cover how numbers are written as bit sequences: bases, negative numbers, overflow, and floating-point numbers. Then they show how letters are turned into numbers with ASCII, Unicode, and UTF-8. The notes go on with adders built from logic gates and follow, step by step, how a processor runs a program in memory with the fetch–decode–execute cycle. The last sections cover the basic design choices of computer architecture and the path of a single line of Java down to machine instructions.

Learning outcomes

Number representation
Convert numbers among binary, octal, decimal, and hexadecimal; explain the consequences of a limited number of bits (negative numbers, overflow, floating point).
Text representation
Distinguish the concepts of ASCII, Unicode, and strings; find the UTF-8 bytes of a character by hand.
Program execution
Explain the stored-program concept and the fetch–decode–execute cycle; trace a small machine program step by step.
Architecture
Interpret the relationship among CPU, memory, registers, and buses; compare the von Neumann and Harvard architectures and the RISC and CISC approaches.

1.3.1Computers and information

A calculator only calculates; a music player only plays music. A computer, with the same hardware, can do all of these and much more. This flexibility has two sources. The first is that every kind of information can be turned into numbers, and numbers into bits. The second is that the instructions telling the machine what to do also sit in memory as numbers. This section introduces the main parts of the computer and the idea of turning information into bits.

1.3.1.1The basic parts of a computer

A desktop computer, a phone, and the control board of a washing machine look very different at first glance. Yet all three contain the same three basic parts.

  • The central processing unit (CPU), or simply the processor, executes instructions. It does jobs such as adding, comparing, and moving a value from one place to another.
  • Memory stores both the data to be processed and the instructions the processor will execute. In these notes the word “memory” means main memory (RAM) unless stated otherwise.
  • Input and output devices (I/O) let the computer exchange data with the outside world. The keyboard, mouse, microphone, and temperature sensor are input devices; the screen, printer, and speaker are output devices.
Inputkeyboard, sensorCPUexecutes instructionsMemoryinstructions + dataOutput: screen, printerwriteread
Figure 1.3.1: The basic parts of a computer. Input devices give data to the CPU. The CPU writes values to memory and reads values from memory. The result goes to an output device.

Figure 1.3.1 shows the flow of data among the parts. A key pressed on the keyboard reaches the CPU through the input device. The CPU can write this value to memory, read it back later, and operate on it. The resulting output is sent to the screen. The two arrows between the CPU and memory show that the two are in constant conversation: as long as the processor runs, it reads instructions and data from memory and writes results to it. The parts inside the CPU and its connection to memory are treated in detail in 1.3.7.

Common mistake

Confusing memory with the disk where files are stored permanently. Main memory (RAM) is fast, but its contents are erased when the power goes off. A disk or SSD is slower but keeps its contents. A program is loaded from disk into memory before it runs; the processor can execute only the instructions in memory.

1.3.1.2From information to bits

Every circuit inside a computer basically tells two states apart: voltage present or absent, switch open or closed. These two states are written as the digits 1 and 0. A single 0 or 1 is called a bit (binary digit). A group of eight bits is called a byte.

A single bit can express only two states. When bits are put side by side, the possibilities multiply. Two bits give 4 different sequences: 00, 01, 10, 11; three bits give 8; eight bits give 28 = 256. The general rule is this: n bits can form 2n different bit sequences. Numbers, letters, the colors of the dots in a picture, and the instructions of a program are stored by pairing them with one of these sequences.

Definition 1.3.1

An encoding is a set of rules that pairs the elements of a kind of information with bit sequences. A data type determines with which encoding a bit sequence in memory is to be read.

This definition has an important consequence: a bit sequence carries no meaning by itself. If the sequence 01000001 is read as an integer, it is 65; if it is read as an ASCII character, it is the letter “A.” The meaning is given by the data type the reading program chooses.

Informationletter “A”EncodingASCII 65Bit sequence01000001Programconvert tolowercase: +32Output“a” on the screen01000001 (65) + 00100000 (32) = 01100001 (97) = “a”
Figure 1.3.2: The journey of the letter “A.” The letter is turned into the number 65 by ASCII, and 65 into the bit sequence 01000001. The program adds 32 to this number and the result is 01100001 = 97; “a” appears on the screen.

Figure 1.3.2 shows the whole chain together. The “A” key is pressed on the keyboard. The encoding rule pairs this letter with the number 65. In memory, 65 sits as the eight-bit sequence 01000001. If a program adds 32 to this number, it gets 01100001, that is, 97. The screen reads this number with the same encoding and draws the letter “a.” The computer does not know how to “make a letter smaller”; it only adds 32 to a number. The meaning is set up by the encoding and the data type. This small example is taken up again with bit operations in 1.3.4.2.

1.3.2Representing integers

A computer’s most basic job is to deal with numbers. This section explains how integers are written with bits. First, how the everyday decimal system works is recalled; the same idea is carried over to the binary system. Then negative numbers and the overflow problem caused by a limited number of bits are covered.

1.3.2.1Positional number systems and the base

When 345 is written in the decimal system, each of the three digits carries a different value. The 5 is in the ones position, the 4 in the tens position, and the 3 in the hundreds position:

345 = 3 · 100 + 4 · 10 + 5 · 1 = 3 · 102 + 4 · 101 + 5 · 100

The value of a digit changes with its position. This is why such systems are called positional number systems. The weight of each position is 10 times the weight of the position to its right. This 10 is called the base (or radix) of the system.

Definition 1.3.2

A positional system with base b uses b digits, from 0 to b − 1. Of the positions numbered 0, 1, 2, … from right to left, position i has weight bi. The value of the number is the sum of each digit multiplied by its own weight.

In computer science four bases are in common use. Table 1.3.1 shows the same number, 13, in all of them. To avoid confusion about which base a number is written in, the base is added to the lower right in small digits: 11012, 158, 1310, D16.

Table 1.3.1: Commonly used number systems. All four examples show the same number (thirteen).
SystemBaseDigitsExampleValue
Binary20–1110121 · 8 + 1 · 4 + 0 · 2 + 1 · 1 = 13
Octal80–71581 · 8 + 5 · 1 = 13
Decimal100–913101 · 10 + 3 · 1 = 13
Hexadecimal160–9, A–FD1613 · 1 = 13

The hexadecimal system needs sixteen digits, but everyday writing has only ten. The letters A–F are used for the six missing digits: A = 10, B = 11, C = 12, D = 13, E = 14, F = 15. In programming languages the base is often marked with a prefix. In Java, 0b1101 is a binary constant and 0xD a hexadecimal one.

1.3.2.2Decimal to binary, binary to decimal

Converting binary to decimal is applying the definition directly. In the binary system the position weights double from right to left: 1, 2, 4, 8, 16, 32, 64, 128, …. The weight of every position that holds a 1 is added to the sum. For example, in 1011012 the 1s are in the 32, 8, 4, and 1 positions: 32 + 8 + 4 + 1 = 45.

The most systematic way to convert decimal to binary is to divide the number by 2 repeatedly. The remainder of each division (0 or 1) is a bit. The process stops when the quotient is 0. The remainders are read from last to first, because the first remainder is the rightmost, that is, the ones position.

Example 1.3.1

Let us convert 45 to binary.

Dividend÷ 2 quotientRemainder (bit)Position weight
452211
221102
11514
5218
21016
10132

The remainders are read from bottom to top: 4510 = 1011012. Check: 32 + 8 + 4 + 1 = 45.

For small numbers a second method is more practical: subtract the largest power of two that fits. The largest power that fits into 45 is 32; the remainder is 13. 8 fits into 13, leaving 5; 4 fits into 5, leaving 1; 1 fits into 1. The powers used are 32, 8, 4, 1, and a 1 is written in these positions and a 0 in the others: 101101.

Java’s ready-made methods do the same conversions. The code below writes 45 in three bases, then converts a binary string back to a number. The last line prints the sum of two constants written with the 0b and 0x prefixes; both are 45, so the result is 90.

int n = 45;
System.out.println(Integer.toBinaryString(n));
System.out.println(Integer.toOctalString(n));
System.out.println(Integer.toHexString(n));
System.out.println(Integer.parseInt("101101", 2));
System.out.println(0b101101 + 0x2D);

Output:

101101
55
2d
45
90

Because Java writes hexadecimal digits in lowercase, 45 appears as “2d.” 2D16 and 2d16 are the same number.

1.3.2.3Octal and hexadecimal: grouping bits

Binary notation is natural for the computer but long and hard to read for people. Writing and reading a 32-bit number with thirty-two digits invites mistakes. The octal and hexadecimal bases are ways of writing long binary numbers briefly. The reason these two bases are chosen is simple: 8 = 23 and 16 = 24.

Thanks to these equalities, no arithmetic is needed for the conversion. The bits are grouped starting from the right: in threes for octal, in fours for hexadecimal. Each group is converted to a single digit. If the leftmost group is incomplete, a 0 is added on its left; leading zeros do not change the value.

45₁₀ =101101₂(32 + 8 + 4 + 1)Groups of 3:101= 5101= 5→ 55₈(5·8 + 5 = 45)Groups of 4:0010= 2 = 21101= 13 = D→ 2D₁₆(2·16 + 13 = 45)
Figure 1.3.3: Converting 4510 = 1011012 to octal and hexadecimal by grouping bits. The groups of three are 101 and 101: 558. The groups of four are 0010 and 1101: 2D16.

In Figure 1.3.3, 101101 is first grouped in threes: 101 | 101. Each group is 5 and the result is 558. Check: 5 · 8 + 5 = 45. When grouping in fours, the group on the right is 1101; on the left only two bits remain (10), and two 0s are added in front to make 0010. Since 0010 = 2 and 1101 = 13 = D, the result is 2D16. Check: 2 · 16 + 13 = 45.

The reverse direction is just as easy. To convert a hexadecimal number to binary, each digit is written with four bits. For example, in A716, A = 1010 and 7 = 0111; the result is 101001112. Its decimal value is 10 · 16 + 7 = 167. Because of this convenience, memory addresses, color codes, and character codes are mostly written in hexadecimal. A byte always corresponds to exactly two hexadecimal digits.

Example 1.3.2

Let us write 156 in binary, octal, and hexadecimal.

  1. Binary: The powers that fit into 156 are 128, 16, 8, and 4 (128 + 16 + 8 + 4 = 156). A 1 is written in these positions: 100111002.
  2. Octal: The groups of three from the right are 100, 011, and 10. The last group is made 010. The groups are 2, 3, 4, so the result is 2348. Check: 2 · 64 + 3 · 8 + 4 = 156.
  3. Hexadecimal: The groups of four are 1001 and 1100, that is, 9 and 12 (C). The result is 9C16. Check: 9 · 16 + 12 = 156.
Common mistake

Reading a number whose base is not written as decimal. “1101” can be one thousand one hundred one, or it can be thirteen. To leave the base unambiguous, a subscript (11012) or a prefix (0b1101, 0x1101) is used. Similarly, 1016 is not ten but 16; in hexadecimal, ten is written with A.

1.3.2.4A limited number of bits and unsigned numbers

On paper the number of digits in a number is unlimited; as many digits as needed are added. In a computer the situation is different. The small, fast storage cells inside the processor are called registers, and the number of bits in each register is fixed: 8, 16, 32, or 64. Every variable in memory also takes a certain number of bits. In Java, byte is 8, short 16, int 32, and long 64 bits.

If all the bits are used for the magnitude of the number, an unsigned number results. With n bits, the numbers from 0 to 2n − 1 can be written. In 8 bits the largest number is 111111112 = 255. Negative numbers cannot be written this way. To write them, one of the bits must be given the job of a “sign.”

1.3.2.5Negative numbers and two’s complement

The first way that comes to mind for writing negative numbers is to set aside the leftmost bit for the sign: 0 for plus, 1 for minus. This method is called sign–magnitude representation, and it has two flaws. First, zero gets two separate writings: 00000000 (+0) and 10000000 (−0). Second, the addition circuit has to look at the signs and do different things for different cases. For this reason modern computers usually store negative integers in two’s complement representation.

Definition 1.3.3

In n-bit two’s complement representation, the weight of the leftmost bit is −2n−1 instead of +2n−1; the weights of the other bits do not change. So if the leftmost bit is 1 the number is negative, and this bit is called the sign bit. The representable range is from −2n−1 to 2n−1 − 1; in 8 bits, −128 … 127.

The definition may look abstract at first reading. An example makes it concrete. In 8 bits, the value of the sequence 11111011 is found by taking the weight of the leftmost bit as −128: −128 + 64 + 32 + 16 + 8 + 2 + 1 = −5. If the same sequence were read as unsigned, it would be 128 + 64 + 32 + 16 + 8 + 2 + 1 = 251. The difference between the two readings is exactly 256, that is, 28. This relationship holds for every negative number: in 8 bits, the bit sequence of −k is the same as the bit sequence of unsigned 256 − k.

00000000110010200113010040101501106011171000−81001−71010−61011−51100−41101−31110−21111−14 bitsfirst bit 1 → negative7 + 1 → −8 (overflow)
Figure 1.3.4: The 4-bit two’s complement circle. The sequences from 0000 to 0111 are the positive numbers 0 … 7; the sequences from 1000 to 1111 are the negative numbers −8 … −1. Every sequence whose first bit is 1 is negative. Adding 1 to 7 moves to −8 on the circle: this is an overflow.

Figure 1.3.4 lays out all the 4-bit sequences like a clock face. Moving clockwise means adding 1. Starting at 0000 and adding 1 each time reaches 1, 2, …, 7. Adding 1 once more to 0111 gives 1000, and this sequence is −8. The dial thus shows a “cliff”: right after the largest positive number comes the smallest negative one. Going counterclockwise, one moves from 0000 to 1111, that is, to −1. It is therefore not surprising that all the bits of −1 are 1.

Two’s complement has three important advantages.

  • A single zero. Zero has only one writing (0000); there is no distinction between plus zero and minus zero.
  • Common arithmetic. The addition circuit uses the same rules for positive and negative numbers. It does not look at the sign of the number; it adds the bits with ordinary binary addition.
  • Easy negation. The negative of a number is found in two simple steps (1.3.2.6).
Table 1.3.2: Signed (two’s complement) and unsigned ranges by number of bits. The corresponding Java types are in the last column.
BitsSigned rangeUnsigned rangeJava type
8−128 … 1270 … 255byte
16−32,768 … 32,7670 … 65,535short
32−2,147,483,648 … 2,147,483,6470 … 4,294,967,295int
64about ±9.22 · 10180 … about 1.84 · 1019long

Note that the range is not symmetric. In 8 bits −128 can be written but +128 cannot. The reason is that one of the 256 sequences is set aside for zero. The remaining 255 sequences are shared between 128 negative and 127 positive numbers.

1.3.2.6How is −5 written?

Two steps are enough to find the negative of a number in two’s complement:

  1. All the bits are flipped (0 ↔ 1). The resulting sequence is called the one’s complement.
  2. 1 is added to the result.
Example 1.3.3

Let us write −5 in 8 bits and check the result.

  1. Write +5: 5 = 4 + 1, so +5 = 00000101.
  2. Flip the bits: 00000101 → 11111010. This sequence is the one’s complement and is not yet −5.
  3. Add 1: 11111010 + 1 = 11111011. The leftmost 1 shows that the number is negative.
  4. Check: 5 + (−5) should be 0. 00000101 + 11111011 = 100000000. The result is 9 bits; the 9th bit does not fit in an 8-bit register and is discarded. What remains is 00000000 = 0.
+500000101−511111011sum100000000the carry out is discardedwhat remains in 8 bits: 00000000 = 0 ✓
Figure 1.3.5: The 8-bit sum of +5 and −5. The sum is 9 bits long. The carried-out 9th bit (the carry) is discarded, and what remains in 8 bits is 00000000 = 0.

The check in Figure 1.3.5 shows the real strength of two’s complement. The addition circuit does not know that −5 is negative. It adds the bits as usual, discards the carried-out bit, and gets the right result. No separate circuit is needed for negative numbers.

The same two steps also work in the opposite direction. To find the magnitude of a negative sequence, the bits are again flipped and 1 is added: 11111011 → 00000100 → 00000101 = 5; so the sequence is −5. In Java the tilde (~) is the operation that flips all the bits, so ~5 + 1 is −5:

byte x = -5;
System.out.println(Integer.toBinaryString(x & 0xFF));
System.out.println(~5 + 1);
System.out.println(Byte.MIN_VALUE + " " + Byte.MAX_VALUE);

Output:

11111011
-5
-128 127

The x & 0xFF in the first line is there to take only the last 8 bits of the byte value. That way the sequence of −5 in memory appears as 11111011. The last line gives the limits of the byte type, as in Table 1.3.2.

Common mistake

Flipping the bits but forgetting to add 1 in two’s complement. 11111010 is the one’s complement and in two’s complement representation it is −6, not −5. After flipping the bits, 1 must always be added: 11111011 = −5.

1.3.2.7Subtraction is really addition: 5 − 9

Another consequence of two’s complement is that the processor needs no separate subtraction circuit. Subtraction is turned into addition by this equality:

a − b = a + (−b)

First the two’s complement of b is found, and then it is added to a. The steps in the slides are written in the pseudocode below. To the right of each line, after the semicolon, is its explanation.

a ← 00000101     ; +5
b ← 00001001     ; +9
inv ← NOT b      ; flip the bits
neg ← inv + 1    ; −9
s ← a + neg      ; 5 + (−9)
print(s)         ; read as signed
Table 1.3.3: Trace of the operation 5 − 9. Each row shows the state after one line of the pseudocode has been executed.
LineVariableBitsExplanation
1a00000101+5
2b00001001+9 = 8 + 1
3inv11110110all bits flipped
4neg111101111 added: −9 (247 = 256 − 9 if read as unsigned)
5s111111005 + 247 = 252; it does not reach 256, so there is no carry
6printed−4sign bit 1, magnitude: flip + 1 → 00000100 = 4

The last row of the table shows how the result is read. Because the leftmost bit of s is 1, the number is negative. To find its magnitude, the bits are flipped again (00000011) and 1 is added (00000100 = 4). So s = −4, and 5 − 9 = −4 is correct.

76543210s11111100sign bit 1 → negativeNOT s00000011+100000100= 4 → s = −4
Figure 1.3.6: Reading the result of 5 − 9. The sign bit of s = 11111100 is 1, so the number is negative. Flipping the bits and adding 1 gives 00000100 = 4; s = −4.

There is a remarkable point here: the processor produces the same sequence 11111100 and does not know how to interpret it. Read as unsigned, this sequence is 252; read as signed, it is −4. The program decides which is correct by looking at the variable’s data type.

1.3.2.8Overflow: 200 + 100 in 8 bits

A limited number of bits means that the result of some operations does not fit in the register. An 8-bit unsigned register holds at most 255. What happens if 200 and 100 are added?

Example 1.3.4
  1. Operands: 200 = 128 + 64 + 8 → 11001000; 100 = 64 + 32 + 4 → 01100100.
  2. True sum: 300 = 256 + 32 + 8 + 4 → 1001011002. The result needs 9 bits.
  3. What stays in the register: The register holds only 8 bits. The 9th bit, with weight 256, is lost and 00101100 = 44 is left.
  4. Shortcut: 300 − 256 = 44.
20011001000+ 10001100100= 3001001011009th bitwhat remains in 8 bits: 00101100 = 44
Figure 1.3.7: 200 + 100 in 8 bits. The true sum 300 = 1001011002 needs 9 bits. The 9th bit (256) does not fit in the register; what remains in 8 bits is 00101100 = 44.
Definition 1.3.4

Overflow is when the true result of an arithmetic operation does not fit in the range of the register or variable that is to hold it. When overflow occurs, the high bits that do not fit are discarded and a wrong value is left in the register.

Overflow occurs with signed numbers too. If 127 + 1 is computed in 8 bits, 01111111 + 1 = 10000000 results, and this sequence is −128. The move from 7 to −8 on the dial in Figure 1.3.4 is the 4-bit counterpart of the same event.

Overflow is a silent error in programs. Java gives no error on integer overflow; the result silently comes out wrong:

byte b = (byte) (100 + 50);
System.out.println(b);
int big = Integer.MAX_VALUE;
System.out.println(big);
System.out.println(big + 1);

Output:

-106
2147483647
-2147483648

In the first line 100 + 50 = 150 is computed and the result is squeezed into 8 bits with (byte). 150 does not fit the byte range; its 8-bit sequence is 10010110, and when this sequence is read as signed it is 150 − 256 = −106. In the following lines 1 is added to the largest value of int and the smallest value results. So when choosing the type of a variable, the largest value it may take should be considered. For example, a country’s population does not fit in a short; the world’s population does not even fit in an int (about 8 billion > 2.1 billion).

1.3.2.9Carry versus signed overflow

The addition circuit can produce two separate warnings, and the two are often confused. The first is the carry out of the leftmost position, that is, the 9th bit. The second is signed overflow. The two are problems of different interpretations.

  • Carry shows that, when the numbers are interpreted as unsigned, the result does not fit in 8 bits. In signed addition the carry is discarded and the result can still be correct.
  • Signed overflow occurs when the sum of two numbers of the same sign comes out with the opposite sign. If the sum of two positives looks negative, or the sum of two negatives looks positive, the result is wrong. The sum of two numbers of different signs never overflows, because the magnitude of the sum cannot exceed the larger of the two numbers.
Table 1.3.4: Four additions in 8 bits. Carry and signed overflow occur independently of each other.
OperationBinary sumCarrySigned overflowResult
5 + (−9)00000101 + 11110111 = 111111000none−4 ✓
(−1) + (−1)11111111 + 11111111 = 1 111111101none−2 ✓
100 + 5001100100 + 00110010 = 100101100yes−106 ✗
(−100) + (−50)10011100 + 11001110 = 1 011010101yes+106 ✗

Table 1.3.4 shows all four possible cases. In the first row there is neither carry nor overflow. In the second row there is a carry, but the result is correct: −1 + (−1) = −2. A carry is a problem only in the unsigned interpretation; read as unsigned, this operation is 255 + 255 = 510, which does not fit in 8 bits. In the third row the sum of two positive numbers has come out negative; there is no carry but there is signed overflow. In the fourth row the sum of two negatives has come out positive; there is both a carry and an overflow.

Example 1.3.5

In 8 bits, is there a carry and signed overflow in the operations 120 + 10 and (−3) + (−5)?

  1. 120 + 10: 01111000 + 00001010 = 10000010. Because the sum fits in 8 bits, the carry is 0. But the sign bit of the sum of two positive numbers has come out 1: there is signed overflow. Read as signed, the sequence is −126; the correct result, 130, does not fit in the 8-bit signed range.
  2. (−3) + (−5): −3 = 11111101, −5 = 11111011. The sum is 1 11111000; the carry is 1 and is discarded. What remains, 11111000, is negative and its magnitude is 00001000 = 8: the result is −8, which is correct. Because the sum of two negatives came out negative, there is no signed overflow.
Common mistake

Taking carry and signed overflow to be the same thing. Carry is a problem of the unsigned interpretation, overflow of the signed one. One can occur without the other: in (−1) + (−1) there is a carry but the result is correct; in 100 + 50 there is no carry but the signed result is wrong.

1.3.3Floating-point numbers

Integers are enough for counting, but most engineering calculations are done with fractional values: the voltage across a resistor may be 3.3 V, the period of a signal 0.000016 s, the distance to a star 4 · 1016 m. This section explains how such numbers are stored in a limited number of bits and what this costs.

1.3.3.1Why floating point?

In scientific notation, very large and very small numbers are written in the same pattern: 4 · 1016, 1.6 · 10−5. The number is split into two parts: the significant digits and the exponent that says where the point is. As the exponent changes, the point “floats” left or right. The floating-point representation in computers applies the same idea with base 2 instead of 10.

This representation has four properties.

  • Wide range. Very large and very small values are stored with the same number of bits. A 32-bit float can hold values between about 1.2 · 10−38 and 3.4 · 1038.
  • Limited precision. The number of significant digits is fixed. A float carries about 7 decimal digits and a double about 15–16. Not every decimal value can be represented exactly in a finite number of bits.
  • Rounding. Digits that cannot be stored are rounded; small differences can appear in the results of calculations.
  • Comparison. Because of these small differences, floating-point results are compared not with exact equality but with a tolerance value.
the stored value when 0.3 is written0.29999999999999998890the result of 0.1 + 0.20.30000000000000004441true 0.3 (cannot be written exactly as a double)gap between two neighboring doubles ≈ 5.55 × 10⁻¹⁷ → 0.1 + 0.2 == 0.3 is false
Figure 1.3.8: The number line around 0.3. When 0.3 is written in a program, the stored double value is 0.29999999999999998890. The result of 0.1 + 0.2 is the next double: 0.30000000000000004441. The true 0.3 lies between these two and cannot be written exactly as a double. The distance between two neighboring doubles is about 5.55 · 10−17.

Figure 1.3.8 shows concretely what limited precision means. Not every point on the number line can be written as a double; only certain points can, and there are gaps between them. 0.3 is not one of these points. When a program writes 0.3, the nearest point is stored. 0.1 and 0.2 cannot be stored exactly either; when their rounded versions are added, the result falls on the next point instead of the rounded version of 0.3. This is why, in Java, 0.1 + 0.2 is printed as 0.30000000000000004 and the comparison 0.1 + 0.2 == 0.3 gives false.

1.3.3.2Converting a decimal fraction to binary

In the binary system, the weights of the positions after the point halve: 1/2, 1/4, 1/8, 1/16, …. For example, 0.1012 = 1/2 + 1/8 = 0.625. To convert a decimal fraction to binary, the reverse of the division method for integers is used.

Definition 1.3.5

Method for converting a fraction to binary: The fraction is multiplied by 2. The integer part of the product (0 or 1) is the next bit after the point. The integer part is dropped and the process continues with the remaining fraction. When the fraction becomes 0, the expansion ends. If a fraction seen before comes up again, the expansion has entered a loop and never ends.

Example 1.3.6

Let us convert 0.375 to binary.

  1. 0.375 × 2 = 0.75 → integer part 0, first bit 0.
  2. 0.75 × 2 = 1.5 → integer part 1, second bit 1; the process continues with the fraction 0.5.
  3. 0.5 × 2 = 1.0 → integer part 1, third bit 1; the fraction became 0 and the expansion ended.

The result is 0.375 = 0.0112. Check: 1/4 + 1/8 = 0.25 + 0.125 = 0.375.

Because the binary expansion of 0.375 is finite, this number is stored exactly in the computer. The reason is that 0.375 is 3/8, and its denominator is a power of 2. The general rule is this: if the denominator of the reduced fraction consists only of powers of 2, the binary expansion is finite; otherwise it repeats forever. 0.5, 0.25, 0.75, and 0.375 are stored exactly. 0.1 = 1/10, 0.2 = 1/5, and 0.3 = 3/10 cannot be stored exactly because their denominators have a factor of 5.

1.3.3.3Why can’t 0.1 be stored exactly?

Let us see step by step what happens when the same method is applied to 0.1.

Table 1.3.5: The binary expansion of 0.1. After the fifth step the fraction becomes 0.2 again and the expansion enters a loop.
StepOperationBitsRemaining fraction
10.1 × 2 = 0.200.2
20.2 × 2 = 0.400.4
30.4 × 2 = 0.800.8
40.8 × 2 = 1.610.6
50.6 × 2 = 1.210.2 (the fraction at step 2)

At the end of the fifth step the fraction is 0.2 again. 0.2 was already processed at the second step; from here on steps 2–5 repeat exactly and the bits 0011 are produced forever:

0.110 = 0.0 0011 0011 0011 …2

Keep multiplying the fraction by 2; the integer part is the next bit0.1 × 2 = 0.2bit 00.2 × 2 = 0.4bit 00.4 × 2 = 0.8bit 00.8 × 2 = 1.6bit 10.6 × 2 = 1.2bit 10.1₁₀ =0.00011…0.2 came back → “0011” goes on foreverCut off at a finite number of bits → small rounding error
Figure 1.3.9: Converting 0.1 to binary. After five multiplications the fraction 0.2 is seen again; the pattern “0011” goes on forever. Cutting it off at a finite number of bits produces a small rounding error.

A computer cannot store infinitely many bits. The expansion is cut off at some point and the last bit is rounded. The stored number is very close to 0.1 but not equal to it. It is like writing 1/3 as 0.3333… in the decimal system: however many digits are written, 1/3 is never reached exactly. The 0.1, which causes no trouble in the decimal system, behaves like 1/3 in the binary system.

Small rounding errors can accumulate in successive operations. The code below adds 0.1 ten times:

double sum = 0.0;
for (int i = 0; i < 10; i++) {
    sum = sum + 0.1;
}
System.out.println(sum);
System.out.println(sum == 1.0);
System.out.println(Math.abs(sum - 1.0) < 1e-9);

Output:

0.9999999999999999
false
true

In mathematics 10 · 0.1 = 1, but the loop produces 0.9999999999999999. This is why the == comparison in the second line gives false. The last line shows the right method: if the absolute value of the difference of two numbers is smaller than a small threshold (here 10−9), the numbers are taken to be “equal.”

Common mistake

Comparing floating-point results with ==. Because 0.1 + 0.2 ≠ 0.3, if (x == 0.3) may be skipped unexpectedly. The right way is to compare with a tolerance of the form Math.abs(a - b) < epsilon. The threshold is chosen according to the scale of the quantities being computed.

1.3.3.4The IEEE 754 format

How floating-point numbers are laid out in bits is set by the IEEE 754 standard, which all processors follow. The standard puts the number in binary scientific form:

value = (−1)sign × 1.fraction × 2(exponent − bias)

The bit sequence is divided into three fields: sign, exponent, and fraction. Table 1.3.6 shows the fields of the two floating-point types in Java.

Table 1.3.6: IEEE 754 formats. The bias is a constant added to the true exponent before it is written to the exponent field.
TypeTotalSignExponentFractionBiasDecimal digits
float32 bits1823127about 7
double64 bits111521023about 15–16

The roles of the fields are as follows.

  • If the sign bit is 0 the number is positive, if 1 negative. Two’s complement is not used in floating-point numbers; the magnitude is always stored as positive.
  • The exponent field holds not the true exponent but the exponent with the bias added. In float the bias is 127. That way negative exponents are also stored as an unsigned number: if the exponent is −4, 123 is written to the field.
  • The fraction field holds the bits after the point. In normal numbers there is always a single 1 to the left of the point. Because this 1 never changes, it is not stored; the standard gains a bit.
00111101110011001100110011001101sign (1)exponent (8 bits)fraction (23 bits)0+01111011₂ = 123exponent = 123 − 127 = −41.10011001100110011001101₂≈ 1.6000000238value = (−1)^sign × 1.fraction × 2^(exponent − 127)0.1 (float) = 0x3DCCCCCD≈ 1.6000000238 × 2⁻⁴ ≈ 0.10000000149
Figure 1.3.10: The 32-bit float representation of 0.1. The sign is 0; the exponent field is 011110112 = 123, so the true exponent is 123 − 127 = −4; the fraction is 1001 1001 … 1101. The value is 1.6000000238 × 2−4 ≈ 0.10000000149 and its hexadecimal form is 3DCCCCCD.

Figure 1.3.10 shows how 0.1 is stored as a float. 0.1 = 1.1001 1001 1001…2 × 2−4. The pattern 1001 in the fraction repeats forever. When it does not fit in 23 bits, the last bit is rounded; this is why 1101 appears at the end of the fraction field instead of 1100. The stored value is exactly 0.100000001490116119384765625: very close to 0.1, but not equal. Java can show this value with all its digits using BigDecimal:

System.out.println(Integer.toHexString(Float.floatToIntBits(-6.25f)));
System.out.println(Integer.toHexString(Float.floatToIntBits(0.1f)));
System.out.println(new java.math.BigDecimal(0.1f));

Output:

c0c80000
3dcccccd
0.100000001490116119384765625

The Float.floatToIntBits method copies the 32 bits of a float as they are into an int; Integer.toHexString then writes these bits in hexadecimal. The c0c80000 in the first line will be found by hand in the next section.

1.3.3.5Encoding −6.25 as a float

The best way to understand IEEE 754 is to encode a number by hand. The steps in the slides are summarized in the pseudocode below:

x ← −6.25
sign ← 1         ; negative
bin ← 110.01      ; 6 = 110, 0.25 = 0.01
norm ← 1.1001 × 2² ; point 2 left
exp ← 2 + 127 = 129 ; 10000001
frac ← 1001 0000… ; leading 1 dropped
print(hex(bits))
Example 1.3.7

Let us find the 32-bit float form of −6.25.

  1. Sign: Because the number is negative, the sign bit is 1. The remaining steps are done on 6.25.
  2. Converting to binary: The integer part is 6 = 1102. For the fraction 0.25: 0.25 × 2 = 0.5 → 0; 0.5 × 2 = 1.0 → 1 and the fraction drops to 0: 0.012. So 6.25 = 110.012. Unlike 0.1, the expansion is finite and the number is stored exactly.
  3. Normalization: The point is moved until a single 1 is left to its left. In 110.01 the point moves 2 positions to the left: 1.1001 × 22. The true exponent is 2.
  4. Exponent field: The bias is added: 2 + 127 = 129 = 100000012.
  5. Fraction field: The leading 1 is not written; only the 1001 after the point is written. The remaining 19 bits are filled with 0: 1001 0000 0000 0000 0000 000.
  6. Combining the bits: 1 | 10000001 | 10010000000000000000000. The 32 bits grouped in fours: 1100 0000 1100 1000 0000 0000 0000 0000 → C0C8000016.
−6.25 = C0C80000₁₆signexponent (8 bits)fraction (23 bits)11000000110010000000000000000000C0C80000
Figure 1.3.11: The 32 bits of −6.25. The sign is 1, the exponent 10000001 (129), the fraction 1001 and nineteen 0s. The groups of four are C, 0, C, 8, 0, 0, 0, 0: −6.25 = C0C8000016.

The C0C80000 found by hand is the same as Java’s result for Float.floatToIntBits(-6.25f) (c0c80000). Reading in the reverse direction is also the reverse of the same steps. For example, the bits of 4128000016 are 0 | 10000010 | 0101000…. The sign is 0, the true exponent is 130 − 127 = 3, and the number is 1.01012 × 23 = 1010.12 = 10.5.

Common mistake

Writing the true exponent in the exponent field, or putting the leading 1 into the fraction field as well. In the −6.25 example, 129 (10000001) is written to the exponent field, not 2 (00000010). The fraction field begins with 1001, not 11001; the 1 to the left of the point is not stored.

1.3.3.6Working with floating-point numbers

Knowing the limits of floating-point numbers turns into three practical rules in everyday programming.

  • Tolerance instead of equality. Two computed values are not compared with ==; the absolute value of their difference is compared with a small threshold.
  • double for precision. About 7 digits of float are too few for most engineering calculations. In Java, fractional constants are double by default, and it is usually the one chosen.
  • Integers for money. In calculations where an error of a kuruş is not acceptable, amounts are kept as integers in kuruş, or in a type that does exact decimal arithmetic (BigDecimal in Java).

The difference between integers and floating-point numbers becomes clear here. Binary representation is exact for every integer that fits in the range: 13 is stored as 13. Floating point, on the other hand, is approximate for some decimal values. Overflow is the typical problem of integers and rounding that of floating-point numbers; both come from the limited number of bits.

1.3.4Representing text

A computer cannot store letters directly; it stores only numbers. To store text, every character is given a number, and this number is written with bits. Which number goes to which character is decided by an encoding table. This section starts from ASCII, the oldest and simplest table, and reaches Unicode, which covers the writing systems of the whole world, and UTF-8, which writes it into bytes.

1.3.4.1ASCII

ASCII (American Standard Code for Information Interchange) pairs the basic Latin letters, digits, punctuation marks, and control characters with numeric codes. It is a 7-bit code defined in the 1960s and contains 27 = 128 characters (0–127). When stored in a byte, the highest bit is 0.

Table 1.3.7: Some ASCII codes. Uppercase letters start at 65, lowercase letters at 97, and digits at 48, and each group is consecutive.
CharacterDecimalHexadecimalBinary (8 bits)
“A”654101000001
“Z”905A01011010
“a”976101100001
“z”1227A01111010
“0”483000110000
“7”553700110111
space322000100000
line end (LF)100A00001010

The last row of the table is a control character. Control characters do not appear as a shape on the screen; they say how the text is to be laid out. The line end (LF, line feed) says the cursor must move to the next line. The first 32 codes of ASCII (0–31) and 127 are of this kind.

The layout of the ASCII table is not random; two properties make some calculations easy.

  • Letters and digits are consecutive. “B” = 66, “C” = 67, and so on. The numeric value of a digit character is found by subtracting the code of “0” from its code: “7” − “0” = 55 − 48 = 7.
  • Between an uppercase and a lowercase letter there is always a difference of 32. “a” − “A” = 97 − 65 = 32. Since 32 = 25, the two letters differ in a single bit.
“A” = 6501000001“a” = 9701100001the 32s positionUppercase and lowercasediffer in only one bit:97 − 65 = 32
Figure 1.3.12: “A” = 65 = 01000001 and “a” = 97 = 01100001 differ only in the bit in the 32s position.
Common mistake

Confusing a digit character with a number. A “7” entered from the keyboard is a character and its code is 55. If 55 rather than 7 goes into a calculation as its numeric value, the result comes out wrong. The right thing is to do the conversion “7” − “0” = 7.

ASCII’s great shortcoming is its coverage. 128 characters are enough for English, but Turkish letters such as “ç, ğ, ı, ö, ş, ü,” the Greek and Arabic alphabets, Chinese characters, and mathematical symbols are not in the table. In the 1980s and 90s separate 8-bit tables were made for each language; the same byte meant “ğ” in one table and a different letter in another. This is mostly why Turkish texts look garbled on another computer. Unicode was developed to resolve this confusion (1.3.4.3).

1.3.4.2Bit operations: changing the case of a letter

That uppercase and lowercase letters differ in a single bit is a good example for introducing bitwise operations. Bitwise operations process the bits of two numbers at the same positions one by one. To change only some bits of a number, a bit mask is used: the positions that are 1 in the mask take part in the operation and the 0 positions are preserved.

The difference between “G” = 71 and “g” = 103 is 32 = 25. So the two letters differ in bit 5 (bits are numbered from the right, starting at 0). As the mask, 00100000, which has only this bit set to 1, is chosen. The pseudocode in the slides is as follows:

c ← 'G'            ; 71 = 01000111
m ← 00100000       ; mask: bit 5 (32)
k ← c OR m         ; set the bit
b ← k AND (NOT m)  ; clear the bit
t ← b XOR m        ; flip the bit
s ← c << 1         ; shift left
Table 1.3.8: Bit operations on the letter “G.” The mask m = 00100000 (32).
OperationBitsValueRule
c = “G”0100011171 = “G”start
c OR m01100111103 = “g”the bit that is 1 in the mask becomes 1
k AND (NOT m)0100011171 = “G”NOT m = 11011111; the bit in the mask is pulled to 0
b XOR m01100111103 = “g”the bit in the mask is flipped
c << 110001110142 = 71 × 2the bits shift one position to the left, a 0 enters from the right
c >> 10010001135 = 71 ÷ 2 (integer part)the bits shift one position to the right

What each operation is good for can be seen in the last column of the table. OR surely makes a bit 1: if the letter is already lowercase it does not change, and if uppercase it becomes lowercase. AND with the inverted mask surely makes a bit 0: the letter goes back to uppercase. XOR flips the bit: an uppercase letter becomes lowercase and a lowercase letter becomes uppercase. If XOR is done a second time with the same mask, the old value comes back; this property is also used in simple encryption methods.

A bit shift moves all the bits together. In a left shift by one, each bit moves up one position and its weight doubles; the value is multiplied by 2. A right shift divides a positive number by 2 and rounds down: 71 >> 1 = 35. For negative odd numbers >> and / give different results: -3 >> 1 = −2 (rounds down), -3 / 2 = −1 (truncates toward zero).

76543210c01000111= 71<< 1each bit one position to the left, a 0 enters from the rights10001110= 142 = 71 × 2
Figure 1.3.13: Shifting “G” = 71 one position to the left. Each bit moves up one position and a 0 enters from the right: 10001110 = 142 = 71 × 2.

In Java, bit operations are written with the operators | (OR), & (AND), ~ (NOT), ^ (XOR), <<, and >>. The char type in Java is a numeric code; so bit operations can be done directly with letters:

char c = 'G';
System.out.println((int) c);
System.out.println((char) (c | 32));
System.out.println((char) ('g' & ~32));
System.out.println((char) (c ^ 32));
System.out.println(c << 1);
System.out.println(c >> 1);

Output:

71
g
G
g
142
35

The result of a bit operation is an int. To see a letter on the screen, the result is converted back to a character with (char). In the last two lines this conversion is not done, so numbers are printed. The same bits appearing as a letter in one place and as a number in another is one more example of the principle in 1.3.1.2, that the data type gives the meaning.

Common mistake

Always adding or subtracting 32 to change the case of a letter. “G” + 32 gives the right result, but “g” + 32 = 135 is an undefined code. Lowercasing with OR and uppercasing with AND do not change a letter that is already in the wanted state; this makes them safer. This method holds only for English letters in ASCII; the Turkish pairs “ı/I” and “i/İ” do not obey this rule.

1.3.4.3Unicode and the code point

Unicode gives a single, universal number to the characters of the world’s writing systems. This number is called the code point and is written in hexadecimal with the prefix “U+.” The code point of “A” is U+0041; this is 65 in decimal and the same as its ASCII code. Unicode deliberately keeps its first 128 code points the same as ASCII. “ğ” is U+011F, “€” is U+20AC, and the grinning-face emoji is U+1F600. Today Unicode contains hundreds of thousands of characters, covering the Turkish letters, various alphabets, mathematical symbols, and emoji.

A code point is only a number. With which bytes the number is written in a file or in memory is a separate decision. The same code point can be stored with different Unicode transformation formats: UTF-8, UTF-16, and UTF-32 are the best known. If it is not known which format a text file was written in when it is opened, the characters look garbled.

charactercode pointUTF-8 bytes (hexadecimal)lengthAU+0041411 byteğU+011FC49F2 bytes€U+20ACE282AC3 bytes😀U+1F600F09F98804 bytes
Figure 1.3.14: The code points and UTF-8 bytes of four characters. “A” (U+0041) is 1 byte: 41. “ğ” (U+011F) is 2 bytes: C4 9F. “€” (U+20AC) is 3 bytes: E2 82 AC. The grinning face (U+1F600) is 4 bytes: F0 9F 98 80.

1.3.4.4UTF-8 encoding: “ğ”

UTF-8 writes Unicode code points as byte sequences of variable length. Small code points take few bytes and large ones many. Which byte has which role is told by the bits at the start of the byte. Table 1.3.9 summarizes the rules.

Table 1.3.9: UTF-8 templates. The bits of the code point are placed, from left to right, in the x positions.
Code point rangeNumber of bitsByte templateExample
U+0000 – U+007F70xxxxxxx“A” → 41
U+0080 – U+07FF11110xxxxx 10xxxxxx“ğ” → C4 9F
U+0800 – U+FFFF161110xxxx 10xxxxxx 10xxxxxx“€” → E2 82 AC
U+10000 – U+10FFFF2111110xxx 10xxxxxx 10xxxxxx 10xxxxxxemoji → F0 9F 98 80

The bits at the start of the templates are labels. A byte that begins with 0 is an ASCII character on its own. 110 means “the first byte of a two-byte character,” 1110 “the first byte of a three-byte character,” and 11110 “the first byte of a four-byte character.” A byte that begins with 10 is a continuation byte. Thanks to these labels, even a program that starts reading in the middle of a text can find the character boundaries.

Example 1.3.8

Let us find the UTF-8 bytes of the letter “ğ.”

  1. Code point: Unicode assigns U+011F to “ğ.” 011F16 = 1 · 256 + 1 · 16 + 15 = 287.
  2. Binary form: 287 = 256 + 16 + 8 + 4 + 2 + 1 = 1000111112. The number does not fit in 7 bits (it is not ASCII) but fits in 11 bits. So 2 bytes are needed. To fill out 11 bits, two 0s are added in front: 00100011111.
  3. Splitting: The two-byte template is 110xxxxx 10xxxxxx and has 5 + 6 = 11 free places. The 11 bits are split from the left as 5 + 6: 00100 | 011111.
  4. Placing: The first byte is 110 + 00100 = 11000100 = C416. The second byte is 10 + 011111 = 10011111 = 9F16.
  5. Result: “ğ” = C4 9F, 2 bytes.
“ğ” → code point U+011F = 28711 bits:001000111115 bits6 bitstemplate:11000100= C4₁₆10011111= 9F₁₆
Figure 1.3.15: The 11 bits of “ğ” = U+011F = 287, placed as 5 + 6 into the template 110xxxxx 10xxxxxx: 11000100 10011111 = C4 9F.

The same method works for “ç” too. The code point of “ç” is U+00E7 = 231; in 11 bits it is written 00011100111. The 5 + 6 split gives 00011 | 100111 and the bytes are 11000011 10100111 = C3 A7. All the letters specific to Turkish are in the range U+0080 – U+07FF; so in UTF-8 each takes 2 bytes. ASCII characters take 1 byte, “€” 3, and an emoji 4.

UTF-8’s greatest advantage is its compatibility with ASCII. Because ASCII characters are written with a single byte and with their ASCII codes, old ASCII texts are also valid UTF-8. The great majority of web pages are written in UTF-8 today. If a UTF-8 file is mistakenly read with an old 8-bit table, the two bytes of “ğ” look like two separate characters; this is why meaningless letters such as “ÄŸ” appear on the screen.

1.3.4.5Strings

A string is a data type made of ordered characters. A name, a sentence, or the whole content of a file is a string. The basic operations on strings are these:

  • Length: the number of characters or code units.
  • Concatenation: joining two strings end to end.
  • Search: finding a character or a substring.
  • Comparison: checking content equality and alphabetical order.
Merhaba␣+DünyaMerhaba␣Dünyalength: 13 characters · 14 bytes in UTF-8 (“ü” takes 2 bytes)
Figure 1.3.16: Concatenating “Merhaba ” and “Dünya” (Turkish for “Hello” and “world”). The result is a string of 13 characters; it takes 14 bytes in UTF-8, because “ü” is 2 bytes.

Figure 1.3.16 shows an important distinction: the number of characters seen on the screen and the number of bytes in memory are not always the same. “Merhaba Dünya” is 13 characters but takes 14 bytes in UTF-8. When allocating memory, calculating the size of a file, or choosing the length of a database field, one must know which of them is being counted. The unit of storage in memory is called a code unit: in UTF-8 a code unit is 1 byte, and in UTF-16, which Java uses, 2 bytes.

String s = "çağ";
System.out.println(s.length());
byte[] b = s.getBytes(java.nio.charset.StandardCharsets.UTF_8);
System.out.println(b.length);
for (byte x : b) {
    System.out.printf("%02X ", x);
}
System.out.println();

Output:

3
5
C3 A7 61 C4 9F 

In Java the length() method counts UTF-16 code units; for “çağ” it gives 3. getBytes turns the string into UTF-8 bytes: “ç” C3 A7, “a” 61, “ğ” C4 9F. The total is 5 bytes. Because an emoji takes two code units in UTF-16, its length() comes out as 2; the idea of a “number of characters” is subtler in Unicode than it looks.

Common mistake

Taking the number of characters to be the number of bytes. In UTF-8 “çağ” (Turkish for “era”) is 3 characters and 5 bytes (ç 2 + a 1 + ğ 2). Ten Turkish letters may not fit in a 10-byte field.

1.3.5Structured information and common mistakes

1.3.5.1From bits to files

Bits do not carry meaning by themselves; they gain meaning by being arranged in larger structures. These structures are built layer by layer.

Bit1Byte01000001Character“A”Fieldname = “Ayşe”Recordno · name · gradeFilerecord 1, 2, 3 …123Ayşe
Figure 1.3.17: Bit, byte, character, field, record, and file. Each level is built from the one before: eight bits make a byte, one or a few bytes make a character, characters make a field, fields make a record, and records make a file.
  • Bit and byte: the smallest units. Eight bits make a byte.
  • Character: one byte in ASCII, one to four bytes in UTF-8.
  • Field: a single meaningful piece of information; for example a name (“Ayşe”) or a grade (85).
  • Record: a collection of related fields. A student record may consist of the fields number, name, and grade.
  • File: a sequence of records and other data stored on disk.

How the bytes inside a file are to be read is defined by the file format: the order of the fields, how many bytes each field has, and in which encoding it is written. The same bytes are a student list to one program and meaningless numbers to another. This is why a jumble of characters appears when an image file is opened with a text editor: the bytes are interpreted with the wrong format.

1.3.5.2Common mistakes in data representation

The mistakes scattered through the sections on data representation are collected in Table 1.3.10 for quick reference.

Table 1.3.10: Common mistakes in data representation and their corrections.
Common mistakeThe correct way
Reading a number without its base: “1101 is one thousand one hundred one”11012 = 13. The base is indicated with a subscript or the 0b/0x prefix.
Taking 1016 to be ten1016 = 16; in hexadecimal, ten is written with A.
Only flipping the bits in two’s complement11111010 is the one’s complement (not −5); adding 1 gives 11111011 = −5.
Comparing floating-point results with ==0.1 + 0.2 ≠ 0.3; check whether |a − b| is smaller than a small tolerance.
Confusing a digit character with a numberThe code of the character “7” is 55; its numeric value is “7” − “0” = 7.
Taking the number of characters to be the number of bytesIn UTF-8 “çağ” is 3 characters and 5 bytes (ç 2 + a 1 + ğ 2).
Confusing carry with signed overflowCarry is a problem of the unsigned interpretation, overflow of the signed one; one can occur without the other.

1.3.6Logic gates and adders

In the earlier sections, addition was always done on paper. The processor, however, does addition with electronic circuits. The building blocks of these circuits are logic gates. This section shows how a few gates come together to add two bits, and then multibit numbers.

1.3.6.1Logic gates and truth tables

Definition 1.3.6

A logic gate is a basic circuit that produces a one-bit output from a one- or two-bit input. The behavior of a gate is fully defined by its truth table, which lists the output for every combination of inputs.

There are four basic gates:

  • AND gives 1 if both inputs are 1.
  • OR gives 1 if at least one of the inputs is 1.
  • XOR (exclusive OR) gives 1 if the inputs differ.
  • NOT reverses its single input.
Table 1.3.11: Truth table of the four basic gates.
ABANDORXORNOT A
000001
010111
100110
111100
ABANDABORABXORANOT
Figure 1.3.18: The circuit symbols of the AND, OR, XOR, and NOT gates. The inputs are on the left and the output on the right. The small circle at the tip of NOT means “inversion.”

The only difference between OR and XOR is in the last row: when both inputs are 1, OR gives 1 and XOR gives 0. This behavior of XOR produces the result digit in binary addition, because the digit of 1 + 1 is 0. AND gives the carry produced in 1 + 1.

Gates are built from a few transistors. A transistor is a small electronic switch opened and closed by a voltage. A processor today contains billions of transistors, and all the operations in the processor are made up of combinations of these basic gates. By connecting gates to one another, more complex logical expressions are computed. For example, in the expression X = NOT (A AND B) OR C, first the parentheses are evaluated, then NOT, and OR last. For A = 1, B = 1, C = 0: A AND B = 1, NOT 1 = 0, and 0 OR 0 = 0. If C = 1, a single 1 would be enough for the OR, so the result would be 1 whatever A and B are.

1.3.6.2The half adder

The sum of two one-bit numbers can be at most 1 + 1 = 2 = 102; the result is written in two bits. The right bit is the result digit (SUM) and the left bit is the carry (CARRY). Table 1.3.12 lists the four cases.

Table 1.3.12: Truth table of the half adder. The SUM column is the same as the table of XOR and the CARRY column the same as the table of AND.
ABA + BCARRYSUM
000 = 00200
011 = 01201
101 = 01201
112 = 10210

Looking carefully at the table, one sees that the SUM column is the same as the table of XOR and the CARRY column the same as that of AND. So two gates are enough to add two bits.

Definition 1.3.7

A half adder is a circuit that adds two one-bit inputs (A, B): SUM = A XOR B gives the result digit and CARRY = A AND B gives the carry.

A1B1XORANDSUM = 0CARRY = 1A XOR BA AND B1 + 1 = 10₂ = 2written in the order (CARRY, SUM)
Figure 1.3.19: The half adder in the case 1 + 1. A and B go to both gates. XOR(1, 1) = 0 gives the result digit and AND(1, 1) = 1 gives the carry: (CARRY, SUM) = 102 = 2.

Figure 1.3.19 shows the circuit’s most interesting case. For 1 + 1, XOR gives 0 and AND gives 1. The result, in the order (CARRY, SUM), is 102 = 2. Like 9 + 1 = 10 in the decimal system, the position overflows and the carry goes to the next position up. The half adder’s name comes from here: it has no input to take an incoming carry, and does only half of the job of addition.

1.3.6.3The full adder

When multibit numbers are added, every column except the rightmost can receive a carry from the column to its right. So three bits are added in each column: A, B, and the incoming carry (Cin). The sum of three bits is at most 3 = 112; it is again written in two bits.

Definition 1.3.8

A full adder is a circuit that adds three one-bit inputs (A, B, Cin) and produces the result digit (SUM) and the outgoing carry (Cout). It is built from two half adders and one OR gate:

t = A XOR B, SUM = t XOR Cin, Cout = (A AND B) OR (t AND Cin)

The first half adder adds A and B and produces the intermediate result t. The second half adder adds the incoming carry to t. A carry can come out of one of the two half adders; it cannot come out of both. The OR gate combines these two possible carries.

Example 1.3.9

Let us find the outputs of the full adder for A = 1, B = 1, Cin = 1.

  1. First half adder: t = 1 XOR 1 = 0; first carry 1 AND 1 = 1.
  2. Second half adder: SUM = 0 XOR 1 = 1; second carry 0 AND 1 = 0.
  3. OR: Cout = 1 OR 0 = 1.
  4. Check: (Cout, SUM) = 112 = 3 = 1 + 1 + 1.

1.3.6.4A four-bit adder: 0110 + 0111

Four full adders are placed side by side and the carry output of each is connected to the carry input of the one to its left. This gives a circuit that adds four-bit numbers. The incoming carry of the rightmost adder is 0. The pseudocode in the slides describes the work the circuit does from right to left:

a ← 0110  ; 6
b ← 0111  ; 7
c ← 0     ; initial carry
for i = 0, 1, 2, 3: ; right to left
  t ← a[i] XOR b[i]
  s[i] ← t XOR c
  c ← (a[i] AND b[i]) OR (t AND c)
print(c, s)
Table 1.3.13: Trace of the full-adder chain for 0110 + 0111 (6 + 7). In each row c is the incoming carry and the last column is the outgoing carry.
ia[i]b[i]incoming cts[i]outgoing c
0010110
1110001
2111011
3001010

The table is read row by row as follows. At i = 0, 0 + 1 + 0 is added: t = 1, s0 = 1; since the two inputs are not both 1, the carry is 0. At i = 1, 1 + 1 + 0 = 2 = 102: digit 0, carry 1. This is the binary counterpart of 5 + 5 = 10 in decimal. At i = 2 the incoming carry is added too: 1 + 1 + 1 = 3 = 112, digit 1, carry again 1. At i = 3, 0 + 0 + 1 = 1; digit 1, carry 0. Because the last carry is 0, the result fits in 4 bits.

FA0full addera0 = 0b0 = 1s0 = 1FA1full addera1 = 1b1 = 1s1 = 0FA2full addera2 = 1b2 = 1s2 = 1FA3full addera3 = 0b3 = 0s3 = 1c=0c=0c=1c=1c=0
Figure 1.3.20: A chain of four full adders (FA0–FA3), for 0110 + 0111. The carry moves from right to left: 0 comes out of FA0, 1 out of FA1, 1 out of FA2, and 0 out of FA3. The result is 11012 = 13 = 6 + 7.

The result is 11012 = 13 = 6 + 7. In this arrangement the carry moves from right to left like a wave; the name of the circuit comes from here: ripple-carry adder. Each full adder has to wait for the carry of the one to its right. As the number of bits grows, the waiting time, that is, the delay, grows too: in a 64-bit ripple-carry adder the leftmost position waits for 63 adders to finish in turn. Real processors therefore use more complex adders that compute the carry in advance; but all of them are built from the same gates.

This circuit is directly connected to the concepts in 1.3.2. The carry coming out of the last full adder is the carry bit in 1.3.2.9. For example, if 1011 + 0111 (11 + 7) is added, a carry of 1 comes out in every column; what remains in 4 bits is 0010 = 2, and the last carry 1 shows that the result does not fit in 4 bits. Thanks to two’s complement, the same circuit also subtracts: for a − b the bits of b are flipped with NOT gates and the rightmost incoming carry is made 1. In this way the rule “flip the bits, add 1” is implemented in hardware with a single circuit.

Common mistake

Trying to build multibit addition from half adders. The half adder has no incoming-carry input; it can be used only in the rightmost column. In the other columns three bits are added, so a full adder is needed.

1.3.7The stored program and the CPU

An adder only adds. What makes a computer general-purpose is the existence of a program that says which operation is to be done in which order. This section explains how a program sits in memory and how the processor runs it step by step.

1.3.7.1The stored-program concept

Some of the first electronic calculators required the wires to be reconnected by hand for a new calculation. Changing a program could take days. An idea put forward in the mid-1940s changed this radically: instructions, too, could be placed in the same memory as the data, as numbers.

Definition 1.3.9

In the stored-program approach, the program’s instructions and the data to be processed are stored in the same memory as numeric codes. The processor reads the instructions from memory in order and executes them.

Memory1000LOAD 10041001ADD 10051002STORE 10061003HALT1004121005810060programdatathe same memory, the same address system
Figure 1.3.21: Program and data in the same memory. At addresses 1000–1003 sit the instructions (LOAD 1004, ADD 1005, STORE 1006, HALT), at addresses 1004–1006 the data (12, 8, 0). Both use the same address system.

This approach has three important consequences.

  • Flexibility: The same hardware does different tasks with different programs. On a computer, a spreadsheet, a game, and a browser run on the same processor.
  • Updating: Behavior can be changed with software without changing the hardware. Updating a phone is writing new instructions into memory.
  • General purpose: A single system can carry out computing, communication, and media tasks together. A program can even read, produce, or translate another program as data; compilers do exactly this.

1.3.7.2The fetch–decode–execute cycle

The processor executes the program in memory with a three-stage cycle that repeats without stopping. Before describing this cycle, two registers need to be introduced.

  • The program counter (PC) holds the memory address of the next instruction.
  • The instruction register (IR) holds the instruction fetched from memory and being executed at that moment.
Definition 1.3.10

The fetch–decode–execute cycle consists of three stages:

  1. Fetch: the instruction at the address in the PC is read and placed in the IR; the PC is incremented by one.
  2. Decode: The control unit splits the instruction in the IR: the opcode says what to do, the operand says what to do it with.
  3. Execute: The ALU or another unit carries out the operation; the result is written to a register or to memory.

Then the cycle starts again with the fetch stage.

1. Fetchinstruction at the PC address → IRPC ← PC + 12. Decodecontrol unitopcode + operand3. ExecuteALU / memory operationresult to register / memoryrepeat
Figure 1.3.22: The fetch, decode, and execute stages form a cycle. In fetch, the instruction at the PC address comes into the IR and the PC goes up by one. In decode, the control unit splits the opcode and the operand. In execute, the ALU or memory operation is done and the result is written to a register or to memory.

There is a reason the PC is incremented in the fetch stage, that is, before the instruction is even executed. The great majority of instructions require moving on to the next instruction; incrementing the PC in advance does this automatically. Branch instructions, on the other hand, change this order in the execute stage by overwriting the PC with a new address (1.3.7.8).

Although the cycle is described as reading from memory, instructions and data often come not from RAM but from the cache inside the processor. Registers and the cache are much faster than RAM. This detail does not change the logic of the cycle; it only raises its speed.

1.3.7.3The main parts of the CPU

CPUControl unitsequencing and signalsALU+ − AND OR compareRegistersPCIRACCCachefrequently used data and instructionsRAM
Figure 1.3.23: Inside the CPU. The control unit manages the sequence and the signals; the ALU does addition, subtraction, AND, OR, and comparison; the registers (PC, IR, ACC) hold intermediate values; the cache brings frequently used data and instructions from RAM and keeps them nearby.

Figure 1.3.23 shows the four main parts of a processor.

  • The control unit manages the order of instructions and the movement of data. It performs the decode stage and sends signals that tell the other units what to do and when.
  • The arithmetic logic unit (ALU) performs arithmetic and logical operations. The adder in 1.3.6.4 is a part of the ALU.
  • Registers: small, fast storage cells used during processing. Besides the PC and IR, the example processor in these notes has an accumulator (ACC) in which calculation results build up.
  • Cache: keeps frequently used data and instructions close to the processor.

1.3.7.4Buses: reading from memory

The CPU is connected to memory and the I/O devices by bundles of parallel wires called buses. There are three separate buses, and each has a different job.

Table 1.3.14: The three buses that connect the CPU to memory and devices.
BusJobDirection
Address busSpecifies the memory or device location to be operated on.one-way: leaves the CPU
Control busCarries read, write, and timing signals.mostly leaves the CPU
Data busCarries data among the CPU, memory, and devices.two-way
Example 1.3.10

The CPU is about to read the value at address 1004; the cell holds 12. The three buses are used in turn as follows:

  1. Address bus: The CPU sends which cell it wants: 1004.
  2. Control bus: The CPU sends the READ signal. For a write, the WRITE signal would go.
  3. Data bus: Memory sends the cell’s contents, 12, to the CPU. The value is loaded into the ACC.
CPUMemory[1004] = 12ACC ← 12Address busControl busData bus12I/O devices are on the same buses too
Figure 1.3.24: The last step of reading from memory. 1004 has gone out on the address bus and the READ signal on the control bus; memory sends the cell’s contents, 12, to the CPU over the data bus.

In a write, the address and control buses are again used from the CPU toward memory, but this time data flows from the CPU to memory. This is why the data bus is two-way. The width of the address bus determines the number of addresses that can be specified: a 16-bit address bus can specify 216 = 65,536 different addresses.

Common mistake

Thinking that the address also travels on the data bus. The number “1004” goes to memory on the address bus; the data bus carries only the cell’s contents (12). The control bus says what is to be done (READ or WRITE).

1.3.7.5Memory addresses

Memory can be pictured as a long array of numbered cells. Each cell has an address, and instructions reach data with this address. The small example memory used in these notes is shown in Table 1.3.15.

Table 1.3.15: Example memory contents. The first four cells are instructions and the last three cells are data.
AddressContentsMeaning
1000LOAD 1004ACC ← mem[1004]
1001ADD 1005ACC ← ACC + mem[1005]
1002STORE 1006mem[1006] ← ACC
1003HALTstop
100412data
10058data
10060result location

The notation “mem[1004]” in the table means “the contents of the cell at address 1004.” Address and contents are different things: at address 1004 there is 12. It is like the difference between a house address and the person living in that house.

In memory there is no physical distinction between instructions and data. Instructions also sit in memory as numbers; the same bit sequence can be interpreted as an instruction or as data. Which one a cell is depends on whether the PC reaches that cell. This is why the HALT instruction is necessary. Without HALT the CPU would move on from 1003 to 1004 and take the 12 there for an instruction and try to run it.

1000LOAD 10041001ADD 10051002STORE 10061003HALT1004121005810060program (instructions)datathe PC advances in order: fetch → decode → executewithout HALT: 12 would be taken for an instruction
Figure 1.3.25: The PC starts at 1000 and fetches the instructions at 1001, 1002, and 1003 in order. The HALT at 1003 stops the CPU; without HALT the 12 at 1004 would be taken for an instruction.

1.3.7.6Multibyte values and byte order

In real computers memory is byte-addressed: each address holds 1 byte. A 32-bit int is 4 bytes and spreads across 4 consecutive addresses. A question then arises: which of the four bytes is written to the lowest address? This order is called endianness, or byte order.

In the value 0x12345678 the most significant byte is 12 and the least significant byte is 78, just as in the number 1234 the 1 is in the thousands position and the 4 in the ones position. There are two common arrangements.

  • Big-endian: the most significant byte is written to the lowest address. From address 100 to 103, 12 34 56 78 is read; the number is laid out in the order it is written on paper. Network protocols use this order; so it is also called network byte order.
  • Little-endian: the least significant byte is written to the lowest address. From address 100 to 103, 78 56 34 12 is read. x86-64 and common ARM systems work in this order.
address 100address 101address 102address 103Big-endian12345678Little-endian785634120x12345678 =12 34 56 78(12 most significant)
Figure 1.3.26: How 0x12345678 is laid out at addresses 100–103. In the big-endian arrangement the most significant byte (12) is at address 100; in the little-endian arrangement it is at address 103.

Both arrangements work correctly; trouble arises only when raw binary data is carried between two systems. The bytes 78 56 34 12 written by a little-endian machine, if read in one go on a big-endian machine, are seen as 0x78563412. File formats and network protocols therefore state the byte order explicitly. In Java the order can be chosen with the ByteBuffer class:

java.nio.ByteBuffer bb = java.nio.ByteBuffer.allocate(4);
bb.order(java.nio.ByteOrder.LITTLE_ENDIAN);
bb.putInt(0x12345678);
for (byte x : bb.array()) {
    System.out.printf("%02X ", x);
}
System.out.println();

Output:

78 56 34 12 

For one-byte values, for example an ASCII character, there is no order problem. UTF-8 is also unaffected by byte order because it is read byte by byte; “ğ” is written in the order C4 9F on every machine.

1.3.7.7Running a program step by step

The parts introduced so far come together in the execution of the small program in Table 1.3.15. The program adds two numbers and writes the result to memory. To the right of each line, after the semicolon, the meaning of the instruction is written:

1000: LOAD  1004 ; ACC ← mem[1004]
1001: ADD   1005 ; ACC ← ACC + mem[1005]
1002: STORE 1006 ; mem[1006] ← ACC
1003: HALT       ; stop
1004: 12         ; data
1005: 8          ; data
1006: 0          ; result

In this example processor, calculations are done in a single register, the ACC. The instructions mean: LOAD a loads the contents of memory address a into the ACC; ADD a adds those contents to the ACC; STORE a writes the ACC to address a; HALT stops the processor. At the start PC = 1000, the address of the first instruction, and ACC = 0.

Table 1.3.16: Fetch–decode–execute trace of the program. Each row shows the register and memory state after the step has finished.
StepStageWhat happens?PCIRACCmem[1006]
0start—1000—00
1fetch1000 goes onto the address bus, LOAD 1004 arrives in the IR over the data bus1001LOAD 100400
2decodeopcode LOAD, address 10041001LOAD 100400
3execute1004 is read, 12 is loaded into the ACC1001LOAD 1004120
4fetchADD 1005 arrives in the IR1002ADD 1005120
5decodeopcode ADD, address 10051002ADD 1005120
6executethe 8 at 1005 is read, the ALU computes 12 + 8 = 201002ADD 1005200
7fetchSTORE 1006 arrives in the IR1003STORE 1006200
8decodeopcode STORE, address 10061003STORE 1006200
9executethe 20 in the ACC is written to 1006 over the data bus1003STORE 10062020
10fetchHALT arrives in the IR1004HALT2020
11decodeopcode HALT → the CPU stops1004HALT2020

Several regular patterns stand out in the trace. The PC changes only in the fetch stages and goes up by one each time. The IR takes the new instruction at each fetch and does not change until that instruction is done. The ACC changes only in the execute stages of LOAD and ADD; memory changes only in the execution of STORE. When the program ends, mem[1006] = 20. Four instructions have been executed in four fetch–decode–execute rounds; because HALT has no work to execute, its round ends in the decode stage.

FETCHDECODEEXECUTECPUPC1001IRLOAD 1004ACC0ALUaddress busdata bus1000LOAD 10041000LOAD 10041001ADD 10051002STORE 10061003HALT1004121005810060
Figure 1.3.27: The first fetch stage (step 1). The 1000 in the PC goes onto the address bus, the instruction LOAD 1004 arrives in the IR over the data bus, and the PC goes up to 1001.
FETCHDECODEEXECUTECPUPC1003IRSTORE 1006ACC20ALUaddress busdata bus1006201000LOAD 10041001ADD 10051002STORE 10061003HALT10041210058100620
Figure 1.3.28: The execute stage of STORE (step 9). The 20 in the ACC is written to address 1006 over the data bus.
Example 1.3.11

What is the result if the places of STORE and ADD in the program are swapped (1001: STORE 1006, 1002: ADD 1005)?

  1. LOAD 1004: ACC = 12.
  2. STORE 1006: the current ACC is written; mem[1006] = 12.
  3. ADD 1005: ACC = 12 + 8 = 20; but this value is never written to memory.
  4. HALT: it stops. Result: ACC = 20, mem[1006] = 12; again 4 instructions have been fetched.

The CPU executes instructions in the order they are written; when the order changes, the result changes.

1.3.7.8Branching: how does the PC change in a loop?

The previous program executed the instructions once from start to end. Real programs make decisions and repeat work. For this, branch instructions are used. A branch instruction overwrites the PC with a new address in the execute stage; so the next fetch happens from somewhere else. The example processor has two branch instructions:

  • JUMP a: unconditional branch; PC ← a.
  • JUMPZ a: conditional branch; if ACC = 0, PC ← a; otherwise the PC stays as it is and the next instruction follows.

The program below counts count down from 2 and adds 2 + 1 to sum. Addresses 1010, 1011, and 1012 hold count, sum, and the constant 1, respectively:

1000: LOAD  1010  ; ACC ← count
1001: JUMPZ 1008  ; jump if ACC = 0
1002: ADD   1011  ; ACC ← ACC + sum
1003: STORE 1011  ; sum ← ACC
1004: LOAD  1010
1005: SUB   1012  ; ACC ← ACC − 1
1006: STORE 1010  ; count ← ACC
1007: JUMP  1000  ; PC ← 1000
1008: HALT
1010: 2   1011: 0   1012: 1

The program is the machine-level counterpart of this loop in Java: while (count != 0) { sum = sum + count; count = count - 1; }. Lines 1000–1001 are the loop condition, lines 1002–1006 the loop body, and line 1007 the return to the start.

Table 1.3.17: Trace of the branching program. Each row shows the state after the instruction has been executed. The PC column is the address to be used at the next fetch.
Instr. no.ExecutedPCACCcountsumExplanation
—start1000020
11000: LOAD 10101001220ACC ← count
21001: JUMPZ 10081002220ACC ≠ 0, no jump
3–4ADD 1011, STORE 10111004222sum = 2 + 0
5–7LOAD, SUB, STORE 10101007112count = 2 − 1
81007: JUMP 10001000112the PC’s 1008 is replaced by 1000
9–16second round (the same 8 instructions)1000003sum = 1 + 2, count = 0
171000: LOAD 10101001003ACC ← 0
181001: JUMPZ 10081008003ACC = 0, jump taken
191008: HALT1009003the CPU stops

The critical moments of the trace are the two branch instructions. At instruction 8, JUMP 1000 is executed. In the fetch stage the PC had already gone up to 1008; execution writes 1000 over this value and the loop goes back to the start. At instruction 18, JUMPZ this time jumps, because the count loaded into the ACC is 0. The PC becomes 1008 and the loop body is skipped. In all, 19 instructions have been fetched: 8 + 8 for two full rounds and 3 for the exit (LOAD, JUMPZ, HALT).

CPUPC1000ACC1Memory1010 count11011 sum21012 one1PC ← 1000 CPUPC1008ACC0Memory1010 count01011 sum31012 one1PC ← 1008
Figure 1.3.29: Two moments of branching. (a) At the end of the first round, JUMP 1000: the PC becomes 1000, count is 1, and sum is 2. (b) In the last round JUMPZ jumps: because ACC = 0, the PC moves to 1008.

The general formula for the number of instructions can also be drawn from the trace. If the count starts from k, the loop turns k rounds and each round is 8 instructions; 3 more instructions are executed at the exit. The total is 8k + 3 instructions: 19 for k = 2 and 43 for k = 5. The final value of the sum variable is k + (k − 1) + … + 1; 15 for k = 5. This count is the first example of how a program’s running time grows with the size of its input.

Common mistake

Thinking that a branch instruction changes the PC in the fetch stage. In fetch, the PC goes up by one as for every instruction (1007 → 1008). The jump is made in the execute stage by overwriting this new value. In a conditional branch, if the condition does not hold the PC is left alone and the incremented value stays in force.

1.3.8Computer architecture

How the parts of a computer are arranged and how the instructions the programmer sees are designed is called architecture. This section covers the arrangement underlying today’s computers, an alternative to it, how instructions are written in bits, and the factors that determine performance.

1.3.8.1The von Neumann architecture

Today’s general-purpose computers rest on an arrangement that uses the stored-program idea. This arrangement is called the von Neumann architecture, after a report John von Neumann wrote in 1945.

CPUControl unitALURegisters (PC, IR, ACC)Memoryprogram instructions + data(shared)single path: bottleneckInputOutput
Figure 1.3.30: The von Neumann architecture. The CPU (control unit, ALU, registers) is connected by a single path to the shared memory that holds program instructions and data together. Input and output devices connect to the CPU.

The architecture has three defining properties.

  • Program instructions and data are kept in shared memory.
  • The CPU processes instructions in sequence; branch instructions can change this order.
  • Instructions and data come over the same path.

The last property has a cost. While the CPU is fetching an instruction, it cannot read data over the same path; the two are carried one after the other. Moreover, over the years processors have developed much faster than memory. As a result, CPU–memory transfer limits performance. This situation is called the von Neumann bottleneck. The cache exists to ease this bottleneck.

1.3.8.2Von Neumann and Harvard

A different way around the bottleneck is to keep instructions and data in separate memories. This arrangement is called the Harvard architecture; its name comes from the Harvard Mark I computer, which was built this way.

von NeumannCPUMemoryinstructions + datasingle pathHarvardinstruction memoryCPUdata memory
Figure 1.3.31: On the left, von Neumann: a single memory and a single path. On the right, Harvard: separate instruction and data memories and separate paths. The CPU only reads from the instruction memory; it reads from and writes to the data memory.
Table 1.3.18: Comparison of the von Neumann and Harvard architectures.
Propertyvon NeumannHarvard
MemoryInstructions and data in shared memoryInstructions and data in separate memories
BusOne path: instructions and data are carried in turnTwo paths: instructions and data are read at the same time
FlexibilityA program can be loaded and modified like dataProgram memory is mostly fixed (flash)
Common useGeneral-purpose computersMicrocontrollers, signal processors

The advantage of the Harvard arrangement is speed: while one instruction is being fetched, the data of the previous instruction can be read at the same time. The price is flexibility. In a microcontroller the program is written to flash memory once and does not change while the device runs; for a washing machine this is enough. A general-purpose computer, however, has to load new programs every day.

Today’s processors combine the two arrangements. Main memory is shared; programs and data are loaded into the same RAM. The first-level (L1) cache closest to the core, however, is separate for instructions and data. This hybrid arrangement is called the modified Harvard architecture. The programmer sees the shared memory, while the processor makes use of two separate paths inside.

1.3.8.3Encoding instructions

As a requirement of the stored-program idea, instructions are written in bits as well. A machine instruction usually carries two pieces of information: the operation to be done and the value or address to be used.

  • Opcode (operation code): defines the type of operation; for example ADD.
  • Operand: the register, value, or address to be used in the operation; for example 1005 or R1, R2.
  • Instruction format: determines the number and position of the bit fields. Every architecture has its own format.
  • Instruction set: the complete set of instructions the processor can understand directly.

A hypothetical format is used for the example processor in these notes: the instruction is 16 bits, the first 4 bits are the opcode, and the remaining 12 bits are the address. The opcodes are HALT = 0000, LOAD = 0001, ADD = 0010, STORE = 0011.

ADD 1005 →0010001111101101opcode (4 bits) = 2 → ADDaddress (12 bits) = 1005Example (hypothetical) codes: HALT = 0000 · LOAD = 0001 · ADD = 0010 · STORE = 0011
Figure 1.3.32: A 16-bit instruction word. For ADD 1005 the first 4 bits are the opcode 0010 (ADD), and the remaining 12 bits are the address 1005 = 001111101101.
Example 1.3.12

Let us encode the four instructions of the program in Table 1.3.15 with this format.

  1. Addresses: 1004 = 3EC16 = 0011 1110 1100; 1005 = 3ED16 = 0011 1110 1101; 1006 = 3EE16 = 0011 1110 1110. (Check: 3 · 256 + 14 · 16 + 12 = 1004.)
  2. LOAD 1004: 0001 0011 1110 1100 = 13EC16.
  3. ADD 1005: 0010 0011 1110 1101 = 23ED16.
  4. STORE 1006: 0011 0011 1110 1110 = 33EE16.
  5. HALT: 0000 0000 0000 0000 = 000016; the address field is not used.

With a 12-bit address field, 212 = 4,096 different addresses (0–4095) can be specified. For a larger memory the address field must be widened.

This encoding makes the observation in 1.3.7.5 concrete. The number 12 at address 1004 is written in 16 bits as 0000 0000 0000 1100. The first four bits of this sequence are 0000, that is, the opcode of HALT. If the same bit sequence is read as data it is 12; if read as an instruction it is a HALT instruction.

1.3.8.4Instruction set design: RISC and CISC

There are two main approaches to how an instruction set is designed.

Table 1.3.19: Comparison of the RISC and CISC approaches.
PropertyRISCCISC
Instruction setA small number of simple instructionsA large number of complex instructions
Instruction lengthFixed (e.g., 32 bits)Variable (1–15 bytes in x86-64)
Memory accessOnly LOAD / STORE instructionsOperation instructions can take a memory operand directly
ExampleARM, RISC-Vx86-64

In the RISC (reduced instruction set computer) approach, instructions are simple and of equal length. Only LOAD and STORE access memory; calculations are done only on registers. In the CISC (complex instruction set computer) approach, a single instruction can read from memory, calculate, and write to memory. The difference shows on the operation a = a + b in memory.

RISC:

LOAD  R1, a
LOAD  R2, b
ADD   R1, R1, R2
STORE R1, a

CISC (x86-64):

MOV EAX, [b]
ADD [a], EAX

RISC needs four instructions: two reads, one addition, one write. In x86-64 the job is finished with two instructions: the first brings b into the EAX register, and the second adds it directly to a in memory. The square brackets mean “the memory contents at this address.” But fewer instructions does not mean less work. The second instruction is again split inside the processor into read, add, and write steps. Today x86-64 processors also execute complex instructions by turning them into small RISC-like steps internally. The great majority of phones use ARM and most personal computers use x86-64; in recent years ARM-based laptops have become common as well.

1.3.8.5Architectural limits

However fast a computer is, it works within some limits. Most of these limits are general names for phenomena met separately in these notes.

  • Finite memory: The amount of data that can be stored at one time is limited.
  • Finite speed: Every instruction consumes time and energy.
  • Representation errors: A limited number of bits can produce overflow (1.3.2.8) and rounding (1.3.3.3).
  • The data bottleneck: The CPU can sit idle while waiting for data in memory.
  • The parallelism limit: Not every problem can be parallelized equally. If a step of a job depends on the result of the previous one, as in the ripple-carry adder, the steps cannot be done at the same time.
  • Security: Because programs and data share the same system resources, programs must be isolated from one another. The strength of the stored-program idea, that data can be run like instructions, is also the door to malicious software.
CPU1 cycle ≈ 0.3 ns (3 GHz)RAMaccess ≈ 100 nsnarrow data pathwaiting for data…100 ns ÷ 0.3 ns ≈ 300 cycles: the cache exists to reduce this wait
Figure 1.3.33: The data bottleneck. In a 3 GHz CPU one clock cycle takes about 0.3 ns; a RAM access takes about 100 ns. While waiting for a piece of data, the CPU can waste about 300 cycles.

The numbers in Figure 1.3.33 show the size of the bottleneck. A 3 GHz processor makes 3 · 109 cycles per second; one cycle takes 1 / (3 · 109) s ≈ 0.33 ns. A 100 ns RAM access therefore corresponds to about 100 ÷ 0.33 ≈ 300 cycles. Without a cache the processor would spend most of its time waiting.

1.3.8.6Performance: instruction count, CPI, and clock speed

The question of how fast a processor is cannot be answered with a single number. The time a program spends on the CPU is the product of three factors:

CPU time = instruction count × CPI ÷ clock speed

  • Instruction count: the number of machine instructions the program executes. It depends on the algorithm, the compiler, and the instruction set.
  • CPI (cycles per instruction): how many clock cycles an instruction takes on average. It depends on the processor’s internal design and on memory waits (cache misses).
  • Clock speed: the number of cycles the processor makes per second; 3 GHz means 3 · 109 cycles per second. It depends on the manufacturing technology and on power and heat limits.
Table 1.3.20: CPU time of a program of 2 · 109 instructions in three cases.
CaseClock speedCPITime
Processor A3 GHz1.52 · 109 × 1.5 ÷ (3 · 109) = 1.0 s
Processor B4 GHz2.52 · 109 × 2.5 ÷ (4 · 109) = 1.25 s
A, with a better compiler (1.6 · 109 instructions)3 GHz1.51.6 · 109 × 1.5 ÷ (3 · 109) = 0.8 s
Example 1.3.13

Let us compute the times of processors A and B step by step.

  1. Total cycles (A): 2 · 109 instructions × 1.5 cycles = 3 · 109 cycles.
  2. Time (A): 3 · 109 cycles ÷ (3 · 109 cycles/s) = 1.0 s.
  3. Total cycles (B): 2 · 109 × 2.5 = 5 · 109 cycles.
  4. Time (B): 5 · 109 ÷ (4 · 109) = 1.25 s.
  5. Comparison: 1.25 ÷ 1.0 = 1.25. Although B’s clock speed is higher, A is 1.25 times faster.

The third row of the table shows that a program can speed up even with no change in hardware. If a better compiler brings the same program down to 1.6 · 109 instructions, A’s time falls to 0.8 s. So a single number, for example clock speed alone, does not determine performance. The most reliable way to evaluate a processor is to run real programs on it and measure the time.

Common mistake

Thinking that the processor with the higher GHz value is always faster. Clock speed is only one factor of the equation. Even if a cycle takes less time, if more cycles are needed per instruction (a high CPI), the total time can get longer.

1.3.9Levels of programming abstraction

1.3.9.1From problem to circuit

When a programmer writes total = a + b; in Java, they do not think about transistors, registers, or opcodes. What makes this possible is that computer systems are built in layers. Each layer hides the detail of the one below and offers a more convenient view to the one above. Hiding the detail and showing only what is needed is called abstraction.

Problem and algorithm“add two numbers”High-level language · Javatotal = a + b;Compiler / virtual machineJava bytecode: iaddAssemblyADD R1, bMachine instructions0010 0011 1110 1101Digital circuitsadder circuit · transistorsfrom abstract to concrete
Figure 1.3.34: Levels of abstraction, from abstract to concrete, top to bottom: problem and algorithm (“add two numbers”), high-level language (total = a + b;), compiler or virtual machine (Java bytecode iadd), assembly (ADD R1, b), machine instructions (0010 0011 1110 1101), and digital circuits (adder, transistors). The example lines are for illustration.

Figure 1.3.34 shows the forms the same idea, “add two numbers,” takes through the layers.

  • Problem and algorithm: What is to be done and in which steps, in human language.
  • High-level language: Languages such as Java, Python, and C. It is readable and portable: the same Java code runs on different processors.
  • Compiler or virtual machine: Translates the high-level code to a lower level. The Java compiler first turns the code into bytecode (intermediate code); the Java virtual machine converts this code into the instructions of the processor it runs on.
  • Assembly: Machine instructions written with names a human can read (LOAD, ADD). Each assembly instruction usually corresponds to a single machine instruction.
  • Machine instructions: The bit sequences the processor executes directly. Assembly and machine code are specific to a particular processor architecture: machine code written for ARM does not run on x86-64.
  • Digital circuits: The gates, adders, and transistors that actually execute the instruction.

The value of abstraction is that a person working at each layer needs to know only their own layer and the view offered by the layer just below. An application programmer can write correct programs without knowing the internal structure of the adder. Still, getting to know the lower layers helps one understand the causes of “unexpected” behavior such as overflow and rounding.

1.3.9.2Tracing code: total = a + b

What a single line of Java turns into on the processor can be shown with a register-based assembly language. In memory there are a = 12 and b = 8:

// Java: int total = a + b;
LOAD  R1, a      ; R1 ← a
ADD   R1, b      ; R1 ← R1 + b
STORE R1, total  ; total ← R1
Table 1.3.21: Assembly trace of the line total = a + b.
InstructionWhat happens?R1abtotal
start—01280
LOAD R1, athe value of a is moved from memory to the register121280
ADD R1, bb is read, the ALU computes 12 + 8 = 20, the result is written to R1201280
STORE R1, totalthe 20 in R1 is written to the place of the total variable2012820
CPUR120ALUMemorya12b8total20
Figure 1.3.35: The STORE step. The 20 in R1 is written to memory, to the place of the total variable; the Java line is complete.

A single Java line has turned into three machine instructions. First the value is loaded from memory into a register, because the ALU works only with registers. Then the calculation is done, and last the result is written back to memory. This load–compute–store pattern appears in almost every assignment line on RISC-style processors. With the same template, the line int diff = a - b; turns into the instructions LOAD R1, a, SUB R1, b, STORE R1, diff. In subtraction the order of the operands matters: a is loaded first, then b is subtracted from it.

This small example brings together all the concepts at the beginning of the notes. a and b are two’s complement bit sequences in memory; the ADD instruction sits in memory as a 16-bit number; the processor takes it with the fetch–decode–execute cycle; the chain of full adders does the addition; the result is written to memory over the data bus. The single line the programmer wrote runs by passing through all of these layers.

1.3.10Summary

  • A computer represents all data with bit sequences. n bits give 2n different sequences. The encoding and the data type determine the meaning of a sequence; the same 01000001 is both 65 and “A.”
  • In a positional system, the position weights are powers of the base. Decimal is converted to binary by repeated division by 2. Since 8 = 23 and 16 = 24, binary is converted to octal and hexadecimal by grouping bits in threes and fours from the right.
  • Negative integers are stored in two’s complement: the bits are flipped and 1 is added. The range for n bits is −2n−1 … 2n−1 − 1; in 8 bits, −128 … 127. Subtraction is done by the addition circuit as a + (−b).
  • If the result does not fit in the register, overflow occurs and the high bits are discarded: in 8 bits, 200 + 100 = 44. Carry is a problem of the unsigned interpretation, signed overflow of the signed one; if the sum of two numbers of the same sign comes out with the opposite sign, there is signed overflow.
  • Floating-point numbers are stored according to IEEE 754 with a sign field, a (biased) exponent field, and a fraction field: float 1 + 8 + 23 bits, double 1 + 11 + 52 bits. Fractions whose denominator is not a power of 2 (such as 0.1) cannot be stored exactly; floating-point results are compared with a tolerance. Binary representation is exact for integers, while floating point is approximate for some decimals.
  • ASCII is a 7-bit code (128 characters). Unicode gives each character a code point; UTF-8 writes this number in 1–4 bytes: ASCII 1, Turkish letters 2, € 3, emoji 4 bytes. The number of characters and the number of bytes may differ.
  • Bit operations (AND, OR, XOR, NOT, shifts) change individual bits with masks; a left shift multiplies by 2, and a right shift divides positive numbers by 2 (rounding down).
  • Logic gates are the building blocks of circuits such as adders. The half adder produces SUM = A XOR B and CARRY = A AND B; the full adder adds the incoming carry as well. Multibit addition is done with a chain of full adders.
  • In the stored-program approach, instructions and data are kept in the same memory as numbers. The CPU executes the instructions in the fetch–decode–execute cycle with the help of the PC and IR registers. The address, control, and data buses connect the CPU to memory. Branch instructions change the PC in the execute stage and so build loops and decisions.
  • Memory is byte-addressed; multibyte values are written in big-endian or little-endian order.
  • In the von Neumann architecture, instructions and data are in shared memory and on a shared path; this causes the von Neumann bottleneck. The Harvard architecture separates the memories; today’s processors combine the two. RISC works with few, simple instructions and CISC with many, complex ones.
  • CPU time = instruction count × CPI ÷ clock speed; no single number determines performance.
  • High-level languages abstract away hardware details: a single Java line turns into a few machine instructions.
Table 1.3.22: Kinds of calculations solved in these notes and their shortcuts.
CalculationMethodExample
Decimal → binarydivide by 2 repeatedly, read the remainders from last to first45 = 1011012
Binary → octal / hexadecimalgroup in 3s / 4s from the right101101 = 558 = 2D16
Negative (two’s complement)flip the bits, add 1−5 = 11111011
Overflow (8-bit unsigned)subtract 256 from the result200 + 100 → 44
Fraction → binarymultiply by 2 repeatedly, take the integer parts0.375 = 0.0112
IEEE 754 floatsign, exponent + 127, fraction without the leading 1−6.25 = C0C8000016
UTF-8 (2 bytes)11 bits → 110xxxxx 10xxxxxx“ğ” = C4 9F
CPU timeinstruction count × CPI ÷ clock speed2 · 109 × 1.5 ÷ 3 GHz = 1 s

1.3.11Key terms

  • bit / byte
  • encoding
  • data type
  • base (radix)
  • binary / octal / decimal / hexadecimal
  • signed / unsigned
  • one’s complement
  • two’s complement
  • overflow
  • signed overflow
  • carry
  • floating point
  • IEEE 754
  • sign / exponent / fraction
  • bias
  • precision
  • rounding
  • ASCII
  • control character
  • bitwise operation
  • bit mask
  • bit shift
  • Unicode
  • code point
  • UTF-8
  • string
  • code unit
  • field / record / file format
  • logic gate
  • half adder
  • full adder
  • ripple-carry adder
  • stored program
  • fetch–decode–execute cycle
  • program counter (PC)
  • instruction register (IR)
  • accumulator (ACC)
  • register
  • control unit
  • cache
  • data / address / control bus
  • memory address
  • endianness
  • branch
  • von Neumann architecture
  • von Neumann bottleneck
  • Harvard architecture
  • opcode
  • instruction format
  • RISC / CISC
  • cycles per instruction (CPI)
  • abstraction
  • assembly language
  • machine instruction

1.3.12Test Yourself

  1. How is 156 written in binary, octal, and hexadecimal?

    Answer

    Since 156 = 128 + 16 + 8 + 4, it is 100111002. Groups of three: 010 | 011 | 100 → 2348. Groups of four: 1001 | 1100 → 9C16. Check: 9 · 16 + 12 = 156.

  2. How is −20 written in 8-bit two’s complement? Which number is the sequence 10110100?

    Answer

    +20 = 00010100; flip the bits: 11101011; add 1: 11101100 = −20. The sign bit of 10110100 is 1, so the number is negative. Flipping the bits and adding 1 gives 01001100 = 76; the sequence is −76. Check: −128 + 32 + 16 + 4 = −76.

  3. In 8 bits, are there a carry and signed overflow in the operations 90 + (−30) and 70 + 80? Are the results correct?

    Answer

    90 + (−30): 01011010 + 11100010 = 1 00111100. The carry is 1 and is discarded; the remaining 00111100 = 60 is correct. The sum of two numbers with different signs does not overflow. 70 + 80: 01000110 + 01010000 = 10010110. The carry is 0, but the sum of two positives looks negative: there is signed overflow. The sequence reads as −106; the correct result, 150, does not fit in the signed 8-bit range.

  4. What are the binary expansions of 0.625 and 0.2? Which is stored exactly as a double?

    Answer

    0.625 × 2 = 1.25 → 1; 0.25 × 2 = 0.5 → 0; 0.5 × 2 = 1.0 → 1 and the fraction is 0: 0.1012, stored exactly (5/8, the denominator is a power of 2). 0.2 × 2 = 0.4 → 0; 0.8 → 0; 1.6 → 1; 1.2 → 1; then the fraction is 0.2 again: 0.0011 0011…2, it repeats forever and cannot be stored exactly.

  5. What is the 32-bit float form of 0.75 in hexadecimal?

    Answer

    0.75 = 0.112 = 1.1 × 2−1. The sign is 0; the exponent is −1 + 127 = 126 = 01111110; the fraction is 1 followed by twenty-two 0s. The bits: 0 01111110 1000…0 → 0011 1111 0100 0000 … → 3F40000016.

  6. What are the UTF-8 bytes of the letter “ü” (U+00FC)? How many characters and how many bytes is the word “Gün” (Turkish for “day”)?

    Answer

    00FC16 = 252 = 111111002; it does not fit in 7 bits, and in 11 bits it is written 00011111100. The 5 + 6 split: 00011 | 111100. The bytes are 110 00011 = C3 and 10 111100 = BC: “ü” = C3 BC. “Gün” is 3 characters; G and n are 1 byte each and ü is 2, so it is 4 bytes.

  7. 0101 + 0011 are added in a chain of four full adders. What is the carry out at each position, and what are the result and the final carry?

    Answer

    i = 0: 1 + 1 + 0 = 102, digit 0, carry 1. i = 1: 0 + 1 + 1 = 102, digit 0, carry 1. i = 2: 1 + 0 + 1 = 102, digit 0, carry 1. i = 3: 0 + 0 + 1 = 1, digit 1, carry 0. The result is 10002 = 8 = 5 + 3; because the final carry is 0, it fits in 4 bits.

  8. In the branching program, if the count at address 1010 were 3 instead of 2, what would sum be when the program ends? How many instructions would be fetched?

    Answer

    The loop turns 3 rounds and sum = 3 + 2 + 1 = 6. Each round is 8 instructions; at the exit LOAD, JUMPZ, and HALT are fetched: 8 · 3 + 3 = 27 instructions.

  9. How many seconds does a program of 3 · 109 instructions take on a 2 GHz processor with CPI 2 and on a 3 GHz processor with CPI 1.2? How many times faster is the second?

    Answer

    First: 3 · 109 × 2 ÷ (2 · 109) = 3 s. Second: 3 · 109 × 1.2 ÷ (3 · 109) = 1.2 s. 3 ÷ 1.2 = 2.5; the second processor is 2.5 times faster.

  10. How is the 32-bit value 0x0A0B0C0D written to addresses 200–203 on a little-endian machine? If a big-endian machine reads these four bytes in one go, what value does it see?

    Answer

    In the little-endian arrangement the least significant byte goes to the lowest address: 200: 0D, 201: 0C, 202: 0B, 203: 0A. A big-endian machine takes the first byte as the most significant and sees 0x0D0C0B0A.

1.3.13Further reading

  • C. Petzold, Code: The Hidden Language of Computer Hardware and Software (2nd ed., Microsoft Press, 2022): starting from Morse code and circuits with light bulbs, it builds gates, adders, memory, and a simple processor step by step without requiring mathematical background.
  • N. Nisan and S. Schocken, The Elements of Computing Systems (2nd ed., MIT Press, 2021): starting from the NAND gate and having the reader build all the layers up to the ALU, the CPU, the assembler, and the compiler, it works through the levels of abstraction in these notes in a hands-on way.
  • R. E. Bryant and D. R. O’Hallaron, Computer Systems: A Programmer’s Perspective (3rd ed., 2016), Chapter 2: explains the two’s complement representation of integers, overflow, and IEEE 754 from the programmer’s viewpoint and with many examples.
  • D. Goldberg, “What Every Computer Scientist Should Know About Floating-Point Arithmetic,” ACM Computing Surveys 23(1), 1991: the classic article that treats in detail the causes and consequences of rounding errors in floating-point computation.

1.3.14References

  1. D. A. Patterson, J. L. Hennessy, Computer Organization and Design: The Hardware/Software Interface, Morgan Kaufmann.
  2. R. E. Bryant, D. R. O’Hallaron, Computer Systems: A Programmer’s Perspective, 3rd ed., Pearson, 2016.
  3. The Unicode Consortium, The Unicode Standard, https://www.unicode.org/standard/standard.html.
  4. IEEE, IEEE Standard for Floating-Point Arithmetic (IEEE Std 754-2019), 2019.
  5. C. Petzold, Code: The Hidden Language of Computer Hardware and Software, 2nd ed., Microsoft Press, 2022.
  6. N. Nisan, S. Schocken, The Elements of Computing Systems: Building a Modern Computer from First Principles, 2nd ed., MIT Press, 2021.
  7. D. Goldberg, “What Every Computer Scientist Should Know About Floating-Point Arithmetic,” ACM Computing Surveys, 23(1), 5–48, 1991.