Chapter 1.1: Computers

Object Oriented Programming with Java
Basic partsBinary numbersTwo's complementFloating point ASCII and UnicodeStringsStored programvon Neumann architecture
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Hardware

Explain what the CPU, memory, disk and bus do; trace how a program runs through the fetch–decode–execute cycle.

Numbers

Convert between binary, octal, hexadecimal and decimal; add in binary and form negative numbers with two's complement.

Text

Explain how ASCII, Unicode and UTF-8 differ; show how a string is stored in memory as numbers.

Connecting to Java

Explain the limits of byte and int and overflow via two's complement; work with bases in Java; map assembly instructions to machine code.

Computer Basics

The Basic Parts of a Computer

  • Processor (CPU, central processing unit): the “brain” of the computer; it does all arithmetic and logical work.
  • Memory (RAM, random access memory): holds the running program and its data temporarily. Its size and access speed directly affect how fast the computer is.
  • Disk (HDD / SSD): stores data persistently; nothing is lost when the power goes off.
DiskSSD / HDDMemoryRAMProcessorCPUpersistent · largeslowtemporary · mediumfastcomputesdecidesprogram and data load →
Kitchen analogy: the cook is the CPU, the counter is RAM (small but within reach), the pantry is the disk (large but far away). The cook brings ingredients from the pantry to the counter and works there.

Computer Basics

How a Computer Works, and Programming

The basic steps:

  1. The processor receives instructions.
  2. It carries them out in order.
  3. The results go to the user or to other software.

Programming is writing instructions, in a form the computer understands, so that it performs the task we want.

Our first Java program: a single instruction, “print to the screen”.

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Output:

Hello, World!

Instructions written in a language like Java run only after they are translated into machine code the processor understands.

Computer Basics

How Do You Build a Computer?

We build the computer layer by layer, each resting on the one below:

  • First we turn electrical signals into numbers.
  • Numbers represent letters; letters make up text.
  • Sequences of numbers store structured information such as images, sound and video.
  • Instructions too are stored in memory as numbers.
  • The von Neumann architecture ties it all together.
1. Numbersbinary, hex, negatives2. Letters and StringsASCII, Unicode, UTF-83. Structured Informationimages, sound, video4. Stored-Program Conceptinstructions are numbers5. von Neumann ArchitectureCPU · memory · bus

Numbers

From Electrical Signal to Bit

  • At bottom, a computer processes electrical signals by fixed rules; those rules give rise to everything it does.
  • Once signals are tied to numbers and symbols people understand, the computer can give us meaningful information.
  • Signals are handled in binary (base 2): each digit, or bit (binary digit), is either 0 or 1.
  • Every operation is built on this binary foundation.
  • voltagethreshold01101011highlow
01
falsetrue
OffOn
Low voltageHigh voltage
Why two states? Telling “voltage / no voltage” apart reliably despite noise is far easier than distinguishing ten voltage levels.

8 bits = 1 byte. Memory and file sizes are measured in bytes: 1 KB ≈ 1000 bytes, 1 KiB = 1024 bytes.

Numbers

Place Value: 13 = 1101₂

  • An integer is written as a sum of powers of 2, each used 0 or 1 times.
  • Four consecutive powers (2⁰, 2¹, 2², 2³) cover the integers 0–15.
  • 13₁₀ = 1·2³ + 1·2² + 0·2¹ + 1·2⁰ = 1101₂

The same rule in other bases:

Decimal (10)603₁₀ = 6·10² + 0·10¹ + 3·10⁰
Octal (8)207₈ = 2·8² + 0·8¹ + 7·8⁰ = 135₁₀
Hexadecimal (16)FF₁₆ = 15·16¹ + 15·16⁰ = 255₁₀
2³ = 811·88+2² = 411·44+2¹ = 200·20+2⁰ = 111·118 + 4 + 0 + 1 = 13

The subscript gives the base: 1101₂ is read “one one zero one, binary”, not “one thousand one hundred one”.

Numbers

Any Base, and the Limits of Bits

  • With base b ≥ 2 and d digits you can write every integer from 0 to bd − 1.
  • Digits run from 0 to b − 1 (0–1 in binary, 0–7 in octal, 0–9 and A–F in hex).
  • A 64-bit computer can count, unsigned, up to 2⁶⁴ − 1 = 18,446,744,073,709,551,615.
BitLargest (2d − 1)
415
8255
1665,535
324,294,967,295

Java's integer types are signed: half of the bit patterns go to negatives.

System.out.println(Byte.MAX_VALUE);    // 8 bit
System.out.println(Short.MAX_VALUE);   // 16 bit
System.out.println(Integer.MAX_VALUE); // 32 bit
System.out.println(Long.MAX_VALUE);    // 64 bit
// all 64 bits 1, read unsigned:
System.out.println(Long.toUnsignedString(-1L));

Output:

127
32767
2147483647
9223372036854775807
18446744073709551615

Numbers · Code trace

Decimal to Binary: Repeated Division by 2

n÷ 2rembits""

Start with n = 13.

n÷ 2rembits""

The result string starts empty: bits = "".

n÷ 2rembits""

13 > 0 is true → enter the loop.

n÷ 2rem13→ 61bits""

Remainder 13 % 2 = 1: the rightmost bit not yet written.

n÷ 2rem13→ 61bits1

The remainder goes in front of the string → "1"; n is halved: 13 / 2 = 6 (integer division).

n÷ 2rem13→ 61bits1

6 > 0 is true → enter the loop.

n÷ 2rem13→ 616→ 30bits1

Remainder 6 % 2 = 0: the rightmost bit not yet written.

n÷ 2rem13→ 616→ 30bits01

The remainder goes in front of the string → "01"; n is halved: 6 / 2 = 3 (integer division).

n÷ 2rem13→ 616→ 30bits01

3 > 0 is true → enter the loop.

n÷ 2rem13→ 616→ 303→ 11bits01

Remainder 3 % 2 = 1: the rightmost bit not yet written.

n÷ 2rem13→ 616→ 303→ 11bits101

The remainder goes in front of the string → "101"; n is halved: 3 / 2 = 1 (integer division).

n÷ 2rem13→ 616→ 303→ 11bits101

1 > 0 is true → enter the loop.

n÷ 2rem13→ 616→ 303→ 111→ 01bits101

Remainder 1 % 2 = 1: the rightmost bit not yet written.

n÷ 2rem13→ 616→ 303→ 111→ 01bits1101

The remainder goes in front of the string → "1101"; n is halved: 1 / 2 = 0 (integer division).

n÷ 2rem13→ 616→ 303→ 111→ 01readbits1101

0 > 0 is false → the loop ends. The remainders are read bottom to top.

n÷ 2rem13→ 616→ 303→ 111→ 01readbits1101

The result is printed: 13₁₀ = 1101₂.

public static void main(String[] args) {
  int n = 13;
  String bits = "";
  while (n > 0) {
    int rem = n % 2;
    System.out.println(n + " % 2 = " + rem);
    bits = rem + bits;
    n = n / 2;
  }
  System.out.println("Result: " + bits);
}

Numbers

Base Conversion in Java

System.out.println(Integer.toBinaryString(13));  // binary
System.out.println(Integer.toOctalString(135));  // octal
System.out.println(Integer.toHexString(255));    // hex
System.out.println(Integer.parseInt("1101", 2)); // 2 → 10
System.out.println(Integer.parseInt("207", 8));  // 8 → 10
System.out.println(0b1101 + " " + 0207 + " " + 0xFF);

Output:

1101
207
ff
13
135
13 135 255
0b prefixBinary literal: 0b1101 = 13 (Java 7+).
0 prefixOctal literal: 0207 = 135. 010 is 8, not ten!
0x prefixHex literal: 0xFF = 255. Common for colors and byte values.

Numbers

Addition Follows the Same Rules in Every Base

Whatever the base, the same principles apply: place values, the carry, and a correct result.

¹
57
+28
85

In decimal 7 + 8 = 15 → write 5, carry 1. In binary 1 + 1 = 2 = 10₂ → write 0, carry 1.

carry5728850000101111010010+

Write the two numbers one above the other: 57 = 00111001₂ and 28 = 00011100₂. Addition starts at the right.

carry57288500001011110100101+

Column 1: 1 + 0 = 1 → write 1, no carry.

carry572885000010111101000101+

Column 2: 0 + 0 = 0 → write 0, no carry.

carry5728850000101111011000101+

Column 3: 0 + 1 = 1 → write 1, no carry.

carry572885000010111110011000101+

Column 4: 1 + 1 = 2 = 10₂ → write 0, carry 1.

carry57288500001101111110011000101+

Column 5: 1 + 1 + 1 (carry) = 3 = 11₂ → write 1, carry 1.

carry5728850010011001111110011000101+

Column 6: 1 + 0 + 1 (carry) = 2 = 10₂ → write 0, carry 1.

carry57288500100111001111110011000101+

Column 7: 0 + 0 + 1 (carry) = 1 → write 1, no carry.

carry572885000100111001111110011000101+

Column 8: 0 + 0 = 0 → write 0, no carry. Result: 01010101₂ = 64 + 16 + 4 + 1 = 85 ✓

Numbers

Negative Numbers: Two's Complement

  • Negative integers are usually stored in two's complement.
  • Rule: invert the bits of the positive number, then add 1.
  • The leftmost bit acts as a sign bit: 0 → positive, 1 → negative.
  • Range with 8 bits: −128 … 127. With n bits: −2n−1 … 2n−1 − 1.
+300000011

On an 8-bit computer, 3 is 00000011.

+300000011invert11111100

Step 1: invert every bit (0 ↔ 1): 00000011 → 11111100 (the ones' complement).

+300000011invert11111100+1 → −311111101

Step 2: add 1: 11111100 + 1 → 11111101. That is −3.

+300000011invert11111100+1 → −311111101Check: 00000011 + 11111101 = 1 000000009th bit doesn't fit, dropped → 00000000 = 0 ✓

Why does it work? Adding 3 + (−3), the 9th bit overflows and is dropped, leaving exactly 0: the ordinary adder does the job.

+300000011invert11111100+1 → −311111101−1286432168421−128 + 64 + 32 + 16 + 8 + 4 + 1 = −3

Another view: the leftmost bit has weight −128, so when it is 1 the number is negative.

Numbers

Two's Complement and Overflow in Java

int n = 3;
int neg = ~n + 1; // invert, add 1
System.out.println(neg);
byte b = (byte) 0b11111101;
System.out.println(b);
System.out.println(Integer.toBinaryString(-3));
System.out.println(Byte.MIN_VALUE + " .. "
    + Byte.MAX_VALUE);
-3
-3
11111111111111111111111111111101
-128 .. 127
byte b = 127;
b++;
System.out.println(b);
int m = Integer.MAX_VALUE;
System.out.println(m + 1);
System.out.println(Math.addExact(m, 1));
-128
-2147483648
Exception in thread "main"
  java.lang.ArithmeticException:
  integer overflow
Overflow: when a result doesn't fit the type's range, Java reports no error; the value wraps around like a clock: 127 + 1 → −128. Use Math.addExact for checked addition.

Numbers

Very Large and Very Small Numbers: Floating Point

  • A fixed number of digits can represent only a fixed number of values.
  • For very large or small numbers, the value is split into a fraction (mantissa) and an exponent, stored separately.
  • Example: in the 8-digit form 31415901, the first six digits (314159) are the fraction and the last two (01) the power of 10, i.e. 10¹.
  • Computers apply the same idea in binary: the IEEE 754 standard. In Java, float is 32 bits and double 64.
31415901fraction (6 digits)exponent (2)0.314159 × 10¹ = 3.14159double (64 bits):111-bit exponent52-bit fraction±

Hence the name floating point: as the exponent changes, the decimal point moves: 0.314159 × 10³ = 314.159.

Numbers

Playing with Bits

Clicking a bit flips it 0 ↔ 1. For −3: 3 → invert → +1. The signed value counts the leftmost bit as −128.

Letters and Strings

Letters as Numbers: ASCII

  • To process text, every letter must be mapped to a number: a character encoding.
  • ASCII (American Standard Code for Information Interchange) was published in 1963 by the US standards body ASA (today ANSI).
  • It assigns numbers to upper- and lowercase letters, digits, punctuation and special characters.
  • It is a 7-bit code: 128 characters (0–127). 0–31 and 127 are control characters; 32–126 are printable.
  • 8-bit extensions (e.g. ISO 8859-9 and Windows-1254 for Turkish) put extra letters in 128–255, for 256 symbols.
  • No single 8-bit table is enough for all the world's languages.
CharacterDecimalBinary
'A'651000001
'a'971100001
'0'480110000
space320100000
newline \n100001010
Lowercase = uppercase + 32. In binary they differ in a single bit (2⁵).

Letters and Strings

The ASCII Table: Printable Characters

+0123456789101112131415
32SP32!33"34#35$36%37&38'39(40)41*42+43,44-45.46/47
48048149250351452553654755856957:58;59<60=61>62?63
64@64A65B66C67D68E69F70G71H72I73J74K75L76M77N78O79
80P80Q81R82S83T84U85V86W87X88Y89Z90[91\92]93^94_95
96`96a97b98c99d100e101f102g103h104i105j106k107l108m109n110o111
112p112q113r114s115t116u117v118w119x120y121z122{123|124}125~126DEL127

Code = row + column. Example: 'J' = 64 + 10 = 74. Each cell shows the character above its decimal code.

0–31 are control characters, e.g. 9 tab (\t), 10 newline (\n), 13 carriage return (\r).

Letters and Strings

One Table for Every Language: Unicode

  • Unicode gives every letter, symbol and mark of the world's writing systems a number, its code point: U+0041 = A, U+00E7 = ç.
  • It is developed by the Unicode Consortium (1991) and kept in sync with the international standard ISO/IEC 10646.
  • The first version was 16-bit (65,536 characters). When that ran out, the range grew to U+10FFFF: 1,114,112 code points, over 150,000 characters today.
  • Storing every character in a fixed 32 bits (UTF-32) wastes space on text like English. Hence the UTF (Unicode Transformation Format) encodings.
CharCode pointDecimalUTF-8 bytes
AU+00416541
çU+00E7231C3 A7
ğU+011F287C4 9F
€U+20AC8364E2 82 AC
😀U+1F600128512F0 9F 98 80

The first 128 code points are identical to ASCII.

Letters and Strings

UTF-8: A Variable-Length Encoding

  • Common characters take few bytes, rare ones more: 1–4 bytes.
  • ASCII text is valid UTF-8 as is (backward compatible). The vast majority of web pages today are UTF-8.
  • The leading bits of the first byte tell how many bytes the character spans.
  • UTF-16 writes most characters in 2 bytes (ş = 01 5F, € = 20 AC); Java's char is one UTF-16 unit.
Code pointByte pattern
U+0000–U+007F0xxxxxxx
U+0080–U+07FF110xxxxx 10xxxxxx
U+0800–U+FFFF1110xxxx 10xxxxxx ×2
U+10000–U+10FFFF11110xxx 10xxxxxx ×3
U+00E7 = 231 = 00011 100111 (11 bits)1100001110100111C3A7colored: pattern bits · others: code point bits
String word = "çikolata";
System.out.println(word.length());
System.out.println(word.getBytes(
    StandardCharsets.UTF_8).length);

Output:

8
9

Letters and Strings

An Emoji Is a Character Too

  • Emoji are symbols that quickly convey feelings, expressions and objects; the computer treats them as text.
  • The Unicode Consortium sets the standard: each emoji is a unique code point, e.g. 😀 = U+1F600.
  • Some emoji combine several code points: 👨‍👩‍👧 = man + ZWJ + woman + ZWJ + girl (5 code points; ZWJ = zero-width joiner).
  • The code is the same on every device, so the meaning survives; the drawing (glyph) may differ by vendor.
String face = "😀";
System.out.println(face.length());
System.out.println(
    face.codePointCount(0, face.length()));
String family = "👨‍👩‍👧";
System.out.println(family.length());

Output:

2
1
8
A Java String stores text in UTF-16: a char is 16 bits, and characters above U+FFFF take two chars (a surrogate pair). So length() counts chars, not characters.

Letters and Strings · Code trace

Printing a String's Character Codes

8length0ç1i2k3o4l5a6t7a

In memory, a string is an array of characters plus a length.

8length0ç2311i2k3o4l5a6t7a

i = 0: charAt(0) = 'ç'; the (int) cast gives its code: 231 (Unicode U+00E7).

8length0ç2311i1052k3o4l5a6t7a

i = 1: charAt(1) = 'i'; the (int) cast gives its code: 105.

8length0ç2311i1052k1073o4l5a6t7a

i = 2: charAt(2) = 'k'; the (int) cast gives its code: 107.

8length0ç2311i1052k1073o1114l5a6t7a

i = 3: charAt(3) = 'o'; the (int) cast gives its code: 111.

8length0ç2311i1052k1073o1114l1085a6t7a

i = 4: charAt(4) = 'l'; the (int) cast gives its code: 108.

8length0ç2311i1052k1073o1114l1085a976t7a

i = 5: charAt(5) = 'a'; the (int) cast gives its code: 97.

8length0ç2311i1052k1073o1114l1085a976t1167a

i = 6: charAt(6) = 't'; the (int) cast gives its code: 116.

8length0ç2311i1052k1073o1114l1085a976t1167a97

i = 7: charAt(7) = 'a'; the (int) cast gives its code: 97.

8length0ç2311i1052k1073o1114l1085a976t1167a97

i = 8: 8 < 8 is false → the loop ends.

8length0ç2311i1052k1073o1114l1085a976t1167a97

A newline and the length are printed: length() = 8.

String word = "çikolata";
for (int i = 0; i < word.length(); i++) {
  char ch = word.charAt(i);
  System.out.print((int) ch + " ");
}
System.out.println();
System.out.println("Length: " + word.length());

The length is stored separately; that is how we know where the text ends. “ç” isn't in ASCII: 231 is its Unicode code point (U+00E7), and it is also 231 in Latin-1 and the Turkish ISO 8859-9.

Letters and Strings

Playing with Character Codes

Each box: character · code point (decimal and U+hex) · UTF-8 bytes. Colored boxes are non-ASCII. The first 12 code points are shown.

Structured Information

Every Kind of Information Is Numbers

Sequences of numbers let us store information and interact with the computer.

0,0,00,0,2550,0,0255,255,2550,0,255255,255,2550,0,00,0,2550,0,0Image: pixel = (R, G, B)Sound: pressure samplesFilm: 24–30 frames per secondframe 1frame 2frame 3frame 4
ImagesEach pixel is three numbers (0–255): red, green and blue levels. A blue pixel: (0, 0, 255).
SoundAir pressure is measured at regular intervals (sampling); CD quality is 44,100 samples per second.
FilmA run of images at 24 or 30 frames per second; each frame is a sequence of numbers, like any image.

Structured Information

Example: How Much Space Does a Video Take?

long pixels = 1920L * 1080;  // one Full HD frame
long frame = pixels * 3;      // R, G, B: 3 bytes
long perSecond = frame * 30;     // 30 frames/s
System.out.println("Pixels: " + pixels);
System.out.println("Frame (bytes): " + frame);
System.out.println("1 second (bytes): " + perSecond);
System.out.println("1 minute (MB): "
    + perSecond * 60 / 1_000_000);
// 44.1 kHz, 16 bits (2 bytes), stereo, 1 min
long audio = 44_100L * 2 * 2 * 60;
System.out.println("1 min CD audio (bytes): " + audio);

Output:

Pixels: 2073600
Frame (bytes): 6220800
1 second (bytes): 186624000
1 minute (MB): 11197
1 min CD audio (bytes): 10584000
One minute of uncompressed Full HD video ≈ 11 GB! In practice video and audio are stored compressed (H.264, MP3…), but a compressed file is still a sequence of numbers. Note: 1920L makes the product a long; large results don't fit in an int.

Stored Program

The Stored-Program Concept

  • The core principle of modern computers: instructions are numbers, just like data, and live in the same memory.
  • Together, the instructions and data in memory form the program. Each instruction stands for one task or operation.
  • Instructions are executed sequentially.
  • When a condition holds, the program can jump to a different instruction, so it can take different paths (if and loops build on this later).
  • 200LOAD201ADD202STORE203HALT204102205252060instructionsdata

ENIAC (1945)

  • Programs are set up by hand with cables and switches.
  • A new program means days of rewiring.

EDVAC design (1945)

  • Instructions and data are stored in sequence in memory.
  • Changing the program = writing new numbers to memory: flexible and extensible.

J. von Neumann's 1945 EDVAC report spread the idea; the first machine to run a stored program was the Manchester “Baby” (1948).

Stored Program

The Memory Hierarchy

  • Memory temporarily holds running programs and their data.
  • L1 cache: the fastest, inside the processor.
  • L2 cache: backs up L1 and is larger. Most processors also have an L3.
  • Main memory (RAM): much larger but slower.
  • Memory close to the processor is faster but smaller and costlier; the hierarchy directly affects performance.
Registersbytes · < 1 nsL1 cache32–64 KB · ~1 nsL2 cache256 KB–2 MB · ~4 nsL3 cache8–64 MB · ~15 nsMain memory (RAM)8–64 GB · ~80 nsDisk (SSD / HDD)TB · µs–msfaster

Sizes and times are approximate and vary by processor. 1 ns = one billionth of a second.

Stored Program

The Processor (CPU) and the Bus

Central Processing Unit (CPU)

  • The “brain” of the computer; all computation happens here.
  • Arithmetic logic unit (ALU): does addition, subtraction, comparison and the like.
  • Control unit: decodes instructions and sequences operations.
  • Registers: tiny but very fast storage for temporary values.

The Bus

  • A communication pathway made of many parallel wires.
  • Address signals select which memory cell or device to access.
  • Data signals carry the actual data to process or store.
  • Control signals direct the operation, e.g. “read” or “write”.
CPUALUControlRegisterscompute · control · fast storageaddress busdata buscontrol busMemoryI/O devices
The electronics link: a 32-line address bus can select 2³² addresses → 4 GiB of memory. That is why 32-bit systems could use at most about 4 GB of RAM.

Stored Program

CPU – Memory – Bus – Registers

Main Memory (RAM)0i = 71j = 912k = j + 1003l = i * kCentral Processing Unit (CPU)Control UnitRegistersPC0IR—R1—R2—AC—ALU+ − × ÷resultAddress busData buscontrol: read / write
  • The CPU names the cell it wants on the address bus.
  • The cell's contents travel over the data bus: in (read) or out (write).
  • PC (program counter): address of the next instruction.
  • IR (instruction register): the instruction being decoded.
  • R1, R2, AC (accumulator): intermediate results.
  • The ALU computes with the numbers in registers.

Stored Program

Memory, Addresses and the Program Counter

  • Memory holds data and instructions; a program is a long list of instructions.
  • Every memory cell has an address and holds an instruction or a piece of data encoded as a number.
  • Instructions are fetched one at a time into the processor's registers and executed in order.
  • One of the most important registers is the program counter (PC): it holds the address of the next instruction.
  • Normally the processor moves through addresses in order, but some instructions change the order: “JUMP 7” at 204 sets the PC to 211.
AddressContentsKind
200ADD to R1instruction
201102data
202…
203…
204JUMP 7instruction (jump)
……
211next instructioninstruction

You can't tell from a cell whether it holds an instruction or data: both are numbers. The difference is how the processor uses it.

Stored Program

The Fetch–Decode–Execute Cycle

The fetch–decode–execute cycle describes how the processor runs a program.

  1. Fetch: the processor reads the next instruction from the address in the PC; the PC advances to the next address.
  2. Decode: the instruction is decoded: which operation, which registers, which address? Each instruction has a specific function.
  3. Execute: the operation is carried out: processing data, computing a result or starting an action.

Then the next instruction is fetched, and the cycle repeats continuously as long as the computer is on.

FetchPC → IRExecuteALU / memoryDecodewhat to do?repeatsforever

A 3 GHz processor's clock “ticks” 3 billion times a second; modern processors overlap several instructions (a pipeline).

Stored Program · Step by step

102 + 25 on a Toy Computer

FetchPC → IRExecuteALU / memoryDecodewhat to do?repeatsforever

Program and data are in memory. Initially PC = 200.

FetchPC → IRExecuteALU / memoryDecodewhat to do?repeatsforever

Fetch: the instruction at 200 goes into IR; PC advances to 201.

FetchPC → IRExecuteALU / memoryDecodewhat to do?repeatsforever

Decode: operation = LOAD, target = R1, address = 205.

FetchPC → IRExecuteALU / memoryDecodewhat to do?repeatsforever

Execute: mem[205] = 102 is read into R1.

FetchPC → IRExecuteALU / memoryDecodewhat to do?repeatsforever

Fetch: the instruction at PC = 201 is read; PC becomes 202.

FetchPC → IRExecuteALU / memoryDecodewhat to do?repeatsforever

Decode: operation = ADD: add R1 and mem[206].

FetchPC → IRExecuteALU / memoryDecodewhat to do?repeatsforever

Execute: the ALU computes 102 + 25 = 127 into R1.

FetchPC → IRExecuteALU / memoryDecodewhat to do?repeatsforever

Fetch: the STORE at 202 is read; PC becomes 203.

FetchPC → IRExecuteALU / memoryDecodewhat to do?repeatsforever

Decode: R1 is to be written to address 207 (control bus: “write”).

FetchPC → IRExecuteALU / memoryDecodewhat to do?repeatsforever

Execute: mem[207] ← 127. The result is now in memory.

FetchPC → IRExecuteALU / memoryDecodewhat to do?repeatsforever

Fetch: the HALT at 203 is read; PC becomes 204.

FetchPC → IRExecuteALU / memoryDecodewhat to do?repeatsforever

Decode + Execute: HALT → the processor stops. A Java line like sum = a + b; ends up as instructions like these.

200: LOAD  R1, [205] ; R1 ← mem[205]
201: ADD   R1, [206] ; R1 ← R1 + mem[206]
202: STORE R1, [207] ; mem[207] ← R1
203: HALT            ; stop
204: ...
205: 102             ; data
206: 25              ; data
207: 0               ; result here

von Neumann Architecture

The von Neumann Architecture

  • The hardware blueprint of the stored-program idea: processor, memory, input/output and the bus that connects them.
  • Instructions and data sit in the same memory and travel over the same bus.
  • Each instruction carries an opcode that says which operation to perform.
  • A single bus can leave the processor waiting: the von Neumann bottleneck. That is why caches exist.
Processor (CPU)Control UnitALURegistersPC · IR · R0–R3Inputkeyboard, sensorOutputscreen, motorMemoryinstructions + data (one memory)bus (bottleneck)

By contrast, the Harvard architecture keeps instruction and data memory separate; many microcontrollers, such as the AVR in an Arduino, use it.

von Neumann Architecture

Instructions Are Numbers Too: Encoding

Take a toy computer: 8 bits, 4 registers (R0–R3), 256 8-bit memory cells and 4 instructions: add (00), subtract (01), multiply (10), divide (11).

  • The first 2 bits are the opcode (4 instructions → 2 bits).
  • The next 2 bits are the destination register.
  • The last 4 bits are two source registers (2 bits each).

“Add R0 and R2, store the result in R3” = 0 3 0 2 → 00110010

opcode000 → adddest11R3source 100R0source 210R2

The processor's “decode” step in Java: division by place value!

int instr = 0b00110010;
int opcode = instr / 64;     // first 2 bits
int dest = (instr / 16) % 4;   // next 2 bits
int src1 = (instr / 4) % 4;  // next 2 bits
int src2 = instr % 4;        // last 2 bits
System.out.println(instr);
System.out.println(opcode + " " + dest
    + " " + src1 + " " + src2);

Output:

50
0 3 0 2

von Neumann Architecture · Code trace

Decoding an Instruction: Code Trace

opcodedestsource 1source 200110010instrinstr = 5032 + 16 + 2 = 50

The instruction is an 8-bit number: 00 11 00 10 = 50. Its bits split into four pairs.

opcodedestsource 1source 200110010instropcode = 0 → add50 / 64 = 0

Dividing by 64 = 2⁶ drops the right 6 bits, leaving the first 2: 00 = 0, i.e. add.

opcodedestsource 1source 200110010instrdest = 3 → R350 / 16 = 3, 3 % 4 = 3

Dividing by 16 drops the right 4 bits (0011 = 3); % 4 keeps the last 2: 3 → R3.

opcodedestsource 1source 200110010instrsrc1 = 0 → R050 / 4 = 12, 12 % 4 = 0

Dividing by 4 drops the right 2 bits (001100 = 12); 12 % 4 = 0 → R0.

opcodedestsource 1source 200110010instrsrc2 = 2 → R250 % 4 = 2

% 4 gives the last 2 bits directly: 10 = 2 → R2.

opcodedestsource 1source 200110010instrinstr = 50

The instruction prints as a number: 50.

opcodedestsource 1source 200110010instrR3 ← R0 + R2

Fields: 0 3 0 2. To the processor, the number 50 means “R3 ← R0 + R2”.

int instr = 0b00110010;
int opcode = instr / 64;     // first 2 bits
int dest = (instr / 16) % 4;   // next 2 bits
int src1 = (instr / 4) % 4;  // next 2 bits
int src2 = instr % 4;        // last 2 bits
System.out.println(instr);
System.out.println(opcode + " " + dest
    + " " + src1 + " " + src2);

von Neumann Architecture

Assembly Language

  • Assembly language is specific to a processor architecture: code written for x86 won't run on ARM.
  • Each line usually corresponds to one machine instruction.
  • It matters for understanding how the computer works at a low level.
  • It is used for performance tuning and talking directly to hardware (drivers, embedded systems).
  • MOV AL, 61hassemblerB0 61CPU executesAL = 97
x86 instructionMeaningMachine code
MOV AL, 61hmove 61h (= 97) into register ALB0 61
MOV AX, BXcopy the value in BX to AX66 89 D8
ADD EAX, 10add 10 to EAX83 C0 0A
XOR EAX, EAXclear EAX (x XOR x = 0)31 C0
61h = 0x61 = 97 = ASCII 'a'. Is a byte in memory a number, a letter or an instruction? That depends on how the program uses it.

Summary

Summary

TopicKey points
PartsCPU computes (ALU + control unit + registers); RAM is temporary, disk persistent; bus: address, data, control
Binarybit = 0/1, 8 bits = 1 byte; d digits give 0 … bd − 1; converting: divide by 2, read remainders bottom up
Negativestwo's complement: invert + 1; 8 bits: −128 … 127; past the limit, silent overflow
Floating pointfraction × baseexponent; IEEE 754 float/double; 0.1 + 0.2 ≠ 0.3
TextASCII 7 bits / 128 characters; Unicode code points (U+0000–U+10FFFF); UTF-8 1–4 bytes; Java char = 16-bit UTF-16
Structured infoimage = RGB pixel array, sound = pressure samples, film = sequence of frames
Stored programinstructions are numbers in memory; PC = next address; fetch–decode–execute; jumps change the order
Levelshigh-level language → assembly → machine code (bits); assembly is processor-specific, usually one instruction per line

Summary

Common Mistakes

Literal out of rangebyte b = 200; → error: incompatible types: possible lossy conversion from int to byte. A byte tops out at 127.
Forgetting the L suffixlong x = 3000000000; → error: integer number too large. Write 3000000000L.
Mixing up char and Stringchar c = "A"; → error: incompatible types: String cannot be converted to char. A char takes single quotes: 'A'.
A leading zeroint x = 010; is octal, so its value is 8! And int y = 08; won't compile (error: ';' expected): octal has no digit 8.
Ignoring overflowInteger.MAX_VALUE + 1 raises no error; it becomes −2147483648. Large products need long: 1920L * 1080.
== on floating point0.1 + 0.2 == 0.3 → false. Check that the difference is small instead. Also, "😀".length() is 2, not 1.

Summary

Sample Problems

  1. Write 45 as an 8-bit binary number.
  2. What is 10110110₂ unsigned? And signed, in 8-bit two's complement?
  3. Write −20 in 8-bit two's complement.
  4. What is 0x3F in decimal, binary and octal?
  5. Compute 01101101₂ + 00110110₂. What is the result as a signed 8-bit byte?
  6. What do System.out.println('a' + 'b'); and System.out.println("" + 'a' + 'b'); print?
  7. What does the instruction 10011100 do on the toy computer?
Show answers
  1. 45 = 32 + 8 + 4 + 1 → 00101101.
  2. 128 + 32 + 16 + 4 + 2 = 182; signed: −128 + 54 = −74 (= 182 − 256).
  3. 20 = 00010100 → invert 11101011 → +1 → 11101100 (= 236 = 256 − 20).
  4. 3·16 + 15 = 63; binary 111111; octal 77.
  5. 109 + 54 = 163 = 10100011₂; as a byte the leftmost bit is 1 → −93 (overflow).
  6. 195 (97 + 98: two chars add as numbers) and ab (a string comes first, so they are concatenated).
  7. 10 = multiply, 01 = R1, 11 = R3, 00 = R0 → R1 ← R3 × R0.

Summary

Exercises

  1. What is the range of a 16-bit signed integer (Java short)?
  2. Write the character codes of "Java" in decimal and binary.
  3. How many bytes is an uncompressed 1024 × 768 image at 3 bytes per pixel?
  4. What are length() and the UTF-8 byte count of "ağaç"?
  5. Write a Java program that prints 0 to 15 as 4-digit binary numbers.
  6. How many distinct bytes can a 32-line address bus address?
Answers / hints
  1. −2¹⁵ … 2¹⁵ − 1 = −32768 … 32767 (Short.MIN_VALUE, Short.MAX_VALUE).
  2. J = 74 = 1001010, a = 97 = 1100001, v = 118 = 1110110, a = 97 = 1100001.
  3. 1024 · 768 · 3 = 2,359,296 bytes = 2.25 MiB.
  4. length() = 4; UTF-8: a(1) + ğ(2) + a(1) + ç(2) = 6 bytes.
  5. Inside for (int i = 0; i < 16; i++), print String.format("%4s", Integer.toBinaryString(i)).replace(' ', '0') → 0000, 0001, …, 1111.
  6. 2³² = 4,294,967,296 bytes = 4 GiB.

Summary

References

  • D. A. Patterson and J. L. Hennessy, Computer Organization and Design: The Hardware/Software Interface, RISC-V Edition, 2nd ed., Morgan Kaufmann, 2020.
  • C. Petzold, Code: The Hidden Language of Computer Hardware and Software, 2nd ed., Microsoft Press, 2022.
  • A. B. Downey and C. Mayfield, Think Java, 2nd ed., O'Reilly, 2019 (Chapter 1).
  • Oracle, The Java Tutorials: “Primitive Data Types” and “Characters”.
  • J. Gosling et al., The Java Language Specification, Java SE 21, §3.10 (Literals) and §4.2 (Primitive Types).
  • The Unicode Consortium, The Unicode Standard, unicode.org; IEEE 754-2019, Standard for Floating-Point Arithmetic.
  • J. von Neumann, First Draft of a Report on the EDVAC, 1945.

The End

Chapter 1.1: Computers
Next: Chapter 1.2: Computation and Computational Thinking
1 / 1 Sercan KÜLCÜ. All rights reserved.