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.
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.
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.
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.
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.
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.
| System | Base | Digits | Example | Value |
|---|---|---|---|---|
| Binary | 2 | 0–1 | 11012 | 1 · 8 + 1 · 4 + 0 · 2 + 1 · 1 = 13 |
| Octal | 8 | 0–7 | 158 | 1 · 8 + 5 · 1 = 13 |
| Decimal | 10 | 0–9 | 1310 | 1 · 10 + 3 · 1 = 13 |
| Hexadecimal | 16 | 0–9, A–F | D16 | 13 · 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.
Let us convert 45 to binary.
| Dividend | ÷ 2 quotient | Remainder (bit) | Position weight |
|---|---|---|---|
| 45 | 22 | 1 | 1 |
| 22 | 11 | 0 | 2 |
| 11 | 5 | 1 | 4 |
| 5 | 2 | 1 | 8 |
| 2 | 1 | 0 | 16 |
| 1 | 0 | 1 | 32 |
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
90Because 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.
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.
Let us write 156 in binary, octal, and hexadecimal.
- 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.
- 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.
- Hexadecimal: The groups of four are 1001 and 1100, that is, 9 and 12 (C). The result is 9C16. Check: 9 · 16 + 12 = 156.
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.
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.
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).
| Bits | Signed range | Unsigned range | Java type |
|---|---|---|---|
| 8 | −128 … 127 | 0 … 255 | byte |
| 16 | −32,768 … 32,767 | 0 … 65,535 | short |
| 32 | −2,147,483,648 … 2,147,483,647 | 0 … 4,294,967,295 | int |
| 64 | about ±9.22 · 1018 | 0 … about 1.84 · 1019 | long |
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:
- All the bits are flipped (0 ↔ 1). The resulting sequence is called the one’s complement.
- 1 is added to the result.
Let us write −5 in 8 bits and check the result.
- Write +5: 5 = 4 + 1, so +5 = 00000101.
- Flip the bits: 00000101 → 11111010. This sequence is the one’s complement and is not yet −5.
- Add 1: 11111010 + 1 = 11111011. The leftmost 1 shows that the number is negative.
- 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.
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 127The 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.
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| Line | Variable | Bits | Explanation |
|---|---|---|---|
| 1 | a | 00000101 | +5 |
| 2 | b | 00001001 | +9 = 8 + 1 |
| 3 | inv | 11110110 | all bits flipped |
| 4 | neg | 11110111 | 1 added: −9 (247 = 256 − 9 if read as unsigned) |
| 5 | s | 11111100 | 5 + 247 = 252; it does not reach 256, so there is no carry |
| 6 | printed | −4 | sign 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.
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?
- Operands: 200 = 128 + 64 + 8 → 11001000; 100 = 64 + 32 + 4 → 01100100.
- True sum: 300 = 256 + 32 + 8 + 4 → 1001011002. The result needs 9 bits.
- What stays in the register: The register holds only 8 bits. The 9th bit, with weight 256, is lost and 00101100 = 44 is left.
- Shortcut: 300 − 256 = 44.
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
-2147483648In 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.
| Operation | Binary sum | Carry | Signed overflow | Result |
|---|---|---|---|---|
| 5 + (−9) | 00000101 + 11110111 = 11111100 | 0 | none | −4 ✓ |
| (−1) + (−1) | 11111111 + 11111111 = 1 11111110 | 1 | none | −2 ✓ |
| 100 + 50 | 01100100 + 00110010 = 10010110 | 0 | yes | −106 ✗ |
| (−100) + (−50) | 10011100 + 11001110 = 1 01101010 | 1 | yes | +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.
In 8 bits, is there a carry and signed overflow in the operations 120 + 10 and (−3) + (−5)?
- 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.
- (−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.
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
floatcan hold values between about 1.2 · 10−38 and 3.4 · 1038. - Limited precision. The number of significant digits is fixed. A
floatcarries about 7 decimal digits and adoubleabout 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.
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.
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.
Let us convert 0.375 to binary.
- 0.375 × 2 = 0.75 → integer part 0, first bit 0.
- 0.75 × 2 = 1.5 → integer part 1, second bit 1; the process continues with the fraction 0.5.
- 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.
| Step | Operation | Bits | Remaining fraction |
|---|---|---|---|
| 1 | 0.1 × 2 = 0.2 | 0 | 0.2 |
| 2 | 0.2 × 2 = 0.4 | 0 | 0.4 |
| 3 | 0.4 × 2 = 0.8 | 0 | 0.8 |
| 4 | 0.8 × 2 = 1.6 | 1 | 0.6 |
| 5 | 0.6 × 2 = 1.2 | 1 | 0.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
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
trueIn 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.”
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.
| Type | Total | Sign | Exponent | Fraction | Bias | Decimal digits |
|---|---|---|---|---|---|---|
float | 32 bits | 1 | 8 | 23 | 127 | about 7 |
double | 64 bits | 1 | 11 | 52 | 1023 | about 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
floatthe 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.
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.100000001490116119384765625The 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))Let us find the 32-bit float form of −6.25.
- Sign: Because the number is negative, the sign bit is 1. The remaining steps are done on 6.25.
- 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.
- 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.
- Exponent field: The bias is added: 2 + 127 = 129 = 100000012.
- 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.
- Combining the bits: 1 | 10000001 | 10010000000000000000000. The 32 bits grouped in fours: 1100 0000 1100 1000 0000 0000 0000 0000 → 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.
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. doublefor precision. About 7 digits offloatare too few for most engineering calculations. In Java, fractional constants aredoubleby 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 (
BigDecimalin 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.
| Character | Decimal | Hexadecimal | Binary (8 bits) |
|---|---|---|---|
| “A” | 65 | 41 | 01000001 |
| “Z” | 90 | 5A | 01011010 |
| “a” | 97 | 61 | 01100001 |
| “z” | 122 | 7A | 01111010 |
| “0” | 48 | 30 | 00110000 |
| “7” | 55 | 37 | 00110111 |
| space | 32 | 20 | 00100000 |
| line end (LF) | 10 | 0A | 00001010 |
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.
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| Operation | Bits | Value | Rule |
|---|---|---|---|
c = “G” | 01000111 | 71 = “G” | start |
c OR m | 01100111 | 103 = “g” | the bit that is 1 in the mask becomes 1 |
k AND (NOT m) | 01000111 | 71 = “G” | NOT m = 11011111; the bit in the mask is pulled to 0 |
b XOR m | 01100111 | 103 = “g” | the bit in the mask is flipped |
c << 1 | 10001110 | 142 = 71 × 2 | the bits shift one position to the left, a 0 enters from the right |
c >> 1 | 00100011 | 35 = 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).
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
35The 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.
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.
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.
| Code point range | Number of bits | Byte template | Example |
|---|---|---|---|
| U+0000 – U+007F | 7 | 0xxxxxxx | “A” → 41 |
| U+0080 – U+07FF | 11 | 110xxxxx 10xxxxxx | “ğ” → C4 9F |
| U+0800 – U+FFFF | 16 | 1110xxxx 10xxxxxx 10xxxxxx | “€” → E2 82 AC |
| U+10000 – U+10FFFF | 21 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx | emoji → 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.
Let us find the UTF-8 bytes of the letter “ğ.”
- Code point: Unicode assigns U+011F to “ğ.” 011F16 = 1 · 256 + 1 · 16 + 15 = 287.
- 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.
- Splitting: The two-byte template is
110xxxxx 10xxxxxxand has 5 + 6 = 11 free places. The 11 bits are split from the left as 5 + 6: 00100 | 011111. - Placing: The first byte is 110 + 00100 = 11000100 = C416. The second byte is 10 + 011111 = 10011111 = 9F16.
- Result: “ğ” = C4 9F, 2 bytes.
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.
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.
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.
- 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.
| Common mistake | The 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 ten | 1016 = 16; in hexadecimal, ten is written with A. |
| Only flipping the bits in two’s complement | 11111010 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 number | The code of the character “7” is 55; its numeric value is “7” − “0” = 7. |
| Taking the number of characters to be the number of bytes | In UTF-8 “çağ” is 3 characters and 5 bytes (ç 2 + a 1 + ğ 2). |
| Confusing carry with signed overflow | Carry 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
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.
| A | B | AND | OR | XOR | NOT A |
|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 | 1 |
| 0 | 1 | 0 | 1 | 1 | 1 |
| 1 | 0 | 0 | 1 | 1 | 0 |
| 1 | 1 | 1 | 1 | 0 | 0 |
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.
| A | B | A + B | CARRY | SUM |
|---|---|---|---|---|
| 0 | 0 | 0 = 002 | 0 | 0 |
| 0 | 1 | 1 = 012 | 0 | 1 |
| 1 | 0 | 1 = 012 | 0 | 1 |
| 1 | 1 | 2 = 102 | 1 | 0 |
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.
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.
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.
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.
Let us find the outputs of the full adder for A = 1, B = 1, Cin = 1.
- First half adder: t = 1 XOR 1 = 0; first carry 1 AND 1 = 1.
- Second half adder: SUM = 0 XOR 1 = 1; second carry 0 AND 1 = 0.
- OR: Cout = 1 OR 0 = 1.
- 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)| i | a[i] | b[i] | incoming c | t | s[i] | outgoing c |
|---|---|---|---|---|---|---|
| 0 | 0 | 1 | 0 | 1 | 1 | 0 |
| 1 | 1 | 1 | 0 | 0 | 0 | 1 |
| 2 | 1 | 1 | 1 | 0 | 1 | 1 |
| 3 | 0 | 0 | 1 | 0 | 1 | 0 |
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.
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.
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.
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.
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.
The fetch–decode–execute cycle consists of three stages:
- Fetch: the instruction at the address in the PC is read and placed in the IR; the PC is incremented by one.
- Decode: The control unit splits the instruction in the IR: the opcode says what to do, the operand says what to do it with.
- 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.
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
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.
| Bus | Job | Direction |
|---|---|---|
| Address bus | Specifies the memory or device location to be operated on. | one-way: leaves the CPU |
| Control bus | Carries read, write, and timing signals. | mostly leaves the CPU |
| Data bus | Carries data among the CPU, memory, and devices. | two-way |
The CPU is about to read the value at address 1004; the cell holds 12. The three buses are used in turn as follows:
- Address bus: The CPU sends which cell it wants: 1004.
- Control bus: The CPU sends the READ signal. For a write, the WRITE signal would go.
- Data bus: Memory sends the cell’s contents, 12, to the CPU. The value is loaded into the ACC.
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.
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.
| Address | Contents | Meaning |
|---|---|---|
| 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 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.
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.
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 ; resultIn 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.
| Step | Stage | What happens? | PC | IR | ACC | mem[1006] |
|---|---|---|---|---|---|---|
| 0 | start | — | 1000 | — | 0 | 0 |
| 1 | fetch | 1000 goes onto the address bus, LOAD 1004 arrives in the IR over the data bus | 1001 | LOAD 1004 | 0 | 0 |
| 2 | decode | opcode LOAD, address 1004 | 1001 | LOAD 1004 | 0 | 0 |
| 3 | execute | 1004 is read, 12 is loaded into the ACC | 1001 | LOAD 1004 | 12 | 0 |
| 4 | fetch | ADD 1005 arrives in the IR | 1002 | ADD 1005 | 12 | 0 |
| 5 | decode | opcode ADD, address 1005 | 1002 | ADD 1005 | 12 | 0 |
| 6 | execute | the 8 at 1005 is read, the ALU computes 12 + 8 = 20 | 1002 | ADD 1005 | 20 | 0 |
| 7 | fetch | STORE 1006 arrives in the IR | 1003 | STORE 1006 | 20 | 0 |
| 8 | decode | opcode STORE, address 1006 | 1003 | STORE 1006 | 20 | 0 |
| 9 | execute | the 20 in the ACC is written to 1006 over the data bus | 1003 | STORE 1006 | 20 | 20 |
| 10 | fetch | HALT arrives in the IR | 1004 | HALT | 20 | 20 |
| 11 | decode | opcode HALT → the CPU stops | 1004 | HALT | 20 | 20 |
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.
What is the result if the places of STORE and ADD in the program are swapped (1001: STORE 1006, 1002: ADD 1005)?
- LOAD 1004: ACC = 12.
- STORE 1006: the current ACC is written; mem[1006] = 12.
- ADD 1005: ACC = 12 + 8 = 20; but this value is never written to memory.
- 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: 1The 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.
| Instr. no. | Executed | PC | ACC | count | sum | Explanation |
|---|---|---|---|---|---|---|
| — | start | 1000 | 0 | 2 | 0 | |
| 1 | 1000: LOAD 1010 | 1001 | 2 | 2 | 0 | ACC ← count |
| 2 | 1001: JUMPZ 1008 | 1002 | 2 | 2 | 0 | ACC ≠ 0, no jump |
| 3–4 | ADD 1011, STORE 1011 | 1004 | 2 | 2 | 2 | sum = 2 + 0 |
| 5–7 | LOAD, SUB, STORE 1010 | 1007 | 1 | 1 | 2 | count = 2 − 1 |
| 8 | 1007: JUMP 1000 | 1000 | 1 | 1 | 2 | the PC’s 1008 is replaced by 1000 |
| 9–16 | second round (the same 8 instructions) | 1000 | 0 | 0 | 3 | sum = 1 + 2, count = 0 |
| 17 | 1000: LOAD 1010 | 1001 | 0 | 0 | 3 | ACC ← 0 |
| 18 | 1001: JUMPZ 1008 | 1008 | 0 | 0 | 3 | ACC = 0, jump taken |
| 19 | 1008: HALT | 1009 | 0 | 0 | 3 | the 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).
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.
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.
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.
| Property | von Neumann | Harvard |
|---|---|---|
| Memory | Instructions and data in shared memory | Instructions and data in separate memories |
| Bus | One path: instructions and data are carried in turn | Two paths: instructions and data are read at the same time |
| Flexibility | A program can be loaded and modified like data | Program memory is mostly fixed (flash) |
| Common use | General-purpose computers | Microcontrollers, 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.
Let us encode the four instructions of the program in Table 1.3.15 with this format.
- Addresses: 1004 = 3EC16 = 0011 1110 1100; 1005 = 3ED16 = 0011 1110 1101; 1006 = 3EE16 = 0011 1110 1110. (Check: 3 · 256 + 14 · 16 + 12 = 1004.)
- LOAD 1004: 0001 0011 1110 1100 = 13EC16.
- ADD 1005: 0010 0011 1110 1101 = 23ED16.
- STORE 1006: 0011 0011 1110 1110 = 33EE16.
- 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.
| Property | RISC | CISC |
|---|---|---|
| Instruction set | A small number of simple instructions | A large number of complex instructions |
| Instruction length | Fixed (e.g., 32 bits) | Variable (1–15 bytes in x86-64) |
| Memory access | Only LOAD / STORE instructions | Operation instructions can take a memory operand directly |
| Example | ARM, RISC-V | x86-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, aCISC (x86-64):
MOV EAX, [b]
ADD [a], EAXRISC 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.
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.
| Case | Clock speed | CPI | Time |
|---|---|---|---|
| Processor A | 3 GHz | 1.5 | 2 · 109 × 1.5 ÷ (3 · 109) = 1.0 s |
| Processor B | 4 GHz | 2.5 | 2 · 109 × 2.5 ÷ (4 · 109) = 1.25 s |
| A, with a better compiler (1.6 · 109 instructions) | 3 GHz | 1.5 | 1.6 · 109 × 1.5 ÷ (3 · 109) = 0.8 s |
Let us compute the times of processors A and B step by step.
- Total cycles (A): 2 · 109 instructions × 1.5 cycles = 3 · 109 cycles.
- Time (A): 3 · 109 cycles ÷ (3 · 109 cycles/s) = 1.0 s.
- Total cycles (B): 2 · 109 × 2.5 = 5 · 109 cycles.
- Time (B): 5 · 109 ÷ (4 · 109) = 1.25 s.
- 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.
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.
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| Instruction | What happens? | R1 | a | b | total |
|---|---|---|---|---|---|
| start | — | 0 | 12 | 8 | 0 |
LOAD R1, a | the value of a is moved from memory to the register | 12 | 12 | 8 | 0 |
ADD R1, b | b is read, the ALU computes 12 + 8 = 20, the result is written to R1 | 20 | 12 | 8 | 0 |
STORE R1, total | the 20 in R1 is written to the place of the total variable | 20 | 12 | 8 | 20 |
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:
float1 + 8 + 23 bits,double1 + 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.
| Calculation | Method | Example |
|---|---|---|
| Decimal → binary | divide by 2 repeatedly, read the remainders from last to first | 45 = 1011012 |
| Binary → octal / hexadecimal | group in 3s / 4s from the right | 101101 = 558 = 2D16 |
| Negative (two’s complement) | flip the bits, add 1 | −5 = 11111011 |
| Overflow (8-bit unsigned) | subtract 256 from the result | 200 + 100 → 44 |
| Fraction → binary | multiply by 2 repeatedly, take the integer parts | 0.375 = 0.0112 |
IEEE 754 float | sign, exponent + 127, fraction without the leading 1 | −6.25 = C0C8000016 |
| UTF-8 (2 bytes) | 11 bits → 110xxxxx 10xxxxxx | “ğ” = C4 9F |
| CPU time | instruction count × CPI ÷ clock speed | 2 · 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
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.
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.
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.
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.
What is the 32-bit
floatform 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.
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.
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.
In the branching program, if the count at address 1010 were 3 instead of 2, what would
sumbe 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.
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.
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
- D. A. Patterson, J. L. Hennessy, Computer Organization and Design: The Hardware/Software Interface, Morgan Kaufmann.
- R. E. Bryant, D. R. O’Hallaron, Computer Systems: A Programmer’s Perspective, 3rd ed., Pearson, 2016.
- The Unicode Consortium, The Unicode Standard, https://www.unicode.org/standard/standard.html.
- IEEE, IEEE Standard for Floating-Point Arithmetic (IEEE Std 754-2019), 2019.
- C. Petzold, Code: The Hidden Language of Computer Hardware and Software, 2nd ed., Microsoft Press, 2022.
- N. Nisan, S. Schocken, The Elements of Computing Systems: Building a Modern Computer from First Principles, 2nd ed., MIT Press, 2021.
- D. Goldberg, “What Every Computer Scientist Should Know About Floating-Point Arithmetic,” ACM Computing Surveys, 23(1), 5–48, 1991.