Unit 1
Basic Computer architecture, Basic Elements of Machine Language, Hack Machine language,
different sets of instructions, Hack programming, Assembly language vs Machine language,
Assembler- assembly process, Hack assembly language, assembly language to binary
conversions.
1. Basic Computer architecture:
A computer is an electronic device that processes data according to instructions provided by
software programs. It takes input (data), processes it using a central processing unit (CPU),
stores information, and produces output (results) to perform various tasks.
1. Input Unit
Purpose: To enter data and instructions into the computer.
Examples shown in the diagram:
Keyboard
Mouse
Scanner
Joystick
Example: These devices convert user input into a form the computer can understand (binary).
2. Central Processing Unit (CPU)
The CPU is the brain of the computer. It performs all processing.
CPU has three main parts:
a) Control Unit (CU)
Controls all operations of the computer
Tells input devices, memory, and ALU what to do and when
Does not perform calculations
Example: It fetches instructions from memory and decodes them.
b) Arithmetic Logic Unit (ALU)
Performs arithmetic operations: addition, subtraction, multiplication, division
Performs logical operations: AND, OR, NOT, comparisons
Example: Calculating marks, comparing two numbers.
c). Memory Unit
Purpose: To store data, instructions, and results.
Stores input data before processing
Stores intermediate results
Stores final output before sending to output devices
In the diagram, data goes from input → memory → CPU
information goes from memory → output
3. Output Unit
Purpose: To display the processed result.
Examples shown in the diagram:
Monitor
Printer
Speaker
Earphones
Example: Converts computer output into a human-readable form.
Working on the Computer (Flow)
1. Input devices give data
2. Data is stored in memory
3. CPU (CU + ALU) processes the data
4. Result is stored in memory
5. Output devices show the information
Summary:
A computer consists of Input Unit, CPU (Control Unit and ALU), Memory Unit, and Output
Unit, which work together to convert data into meaningful information.
Types of Computers
There are various types of computers that are used today based on the need of user. Some of the
types are:
Desktop: Desktops are mainly used for regular use, and they have separate components
mounted together like the monitor, keyboard, mouse, CPU etc. Since the system is
primarily kept on a desk for better usability it is called a desktop.
Laptop: Laptops are a portable version of desktops, with all the components integrated
into a single unit thus providing mobility to the system. They are great for on-the-go
work and come with built-in webcams, Bluetooth and Wi-Fi.
Servers: Servers are special types of computers that are used to manage network
resources. They provide services for other systems and computers. Some of the primary
tasks of servers include creating databases, hosting and providing support to other
applications.
Tablets: Tablets are even more portable than laptops. They are smaller than laptops but
are larger than smartphones. They come with touchscreens which make them perfect for
browsing the web, consuming content and personal communications.
Other devices: Other devices include smartphones, game consoles, Smart TVs etc.
Smart phone and Game Console
Difference between Data and Information
Data is raw, unorganized facts (like numbers, words, symbols) that lack inherent
meaning, while information is data that has been processed, organized, and given context,
making it meaningful and useful for understanding or decision-making, such as a
student's test score (data) becoming the class average (information). Data is the building
block, and information is the structure built from it, adding relevance and purpose.
Key Differences & Examples
Data: 5, white, balloons
Information: "The 5 white balloons that belong to Smith" (ownership added).
Data: 8986526829 (just a number)
Information: "Rita's phone number is 8986526829" (context of ownership/identity).
Data: A list of temperatures: 20°C, 25°C, 18°C
Information: "The average temperature this week was 21°C" (processing to find the
average).
How Different Components Communicate?
Let's discuss some important components of computers in detail,
Component Description
The CPU often referred to as the "brain" of the computer.
It’s responsible for executing instructions, performing
Central calculations, and handling tasks that ensure the system
Processing Unit runs efficiently. The CPU processes input data and
(CPU) transforms it into useful information. It consists of
the Arithmetic Logic Unit (ALU) and Control Unit
(CU).
The main circuit board connects and allows
Motherboard
communication between all computer components.
Component Description
Memory Random Access Memory (RAM) stores data temporarily
(RAM) for quick access while the computer is running.
Includes Hard Disk Drives (HDD) and Solid-State Drives
Storage
(SSD) that store data permanently.
Devices are used to input data into the computer.
Input Devices
Examples: keyboard, mouse, scanner.
Devices that display or output the results of the computer’s
Output Devices
processing. Examples: printer, speakers.
What is a Software?
Software is a set of instructions that tells the computer what to do when to do, it and how
to do it. Examples are the paint that we use in Microsoft, WhatsApp, and games, all are
types of different software. Suppose we want to add 2 numbers and want to know what 2
+ 2 is 4. Then we must give the computer instructions,
Step-1: take 2 values.
Step-2: a store that 2 value
Step-3: add 2 value by using + operator
Step-4: save the answer
An interpreter is responsible for converting the software’s human-readable code into
machine language (binary code) that the CPU understands and executes.
What is Hardware?
Hardware refers to the physical components of a computer that you can touch and see. It
includes all the devices and machinery required to make a computer function. Hardware
performs tasks like storing data, processing information, and displaying results. Without
hardware, there would be no platform for software to run.
Types of Hardware:
Central Processing Unit (CPU) - Executes instructions and performs calculations.
Memory (RAM) - Temporarily stores data that the CPU needs during operation.
Storage Devices (HDD/SSD) - Store data permanently, even when the computer is turned
off.
Input Devices - Allow users to interact with the computer (e.g., keyboard, mouse).
Output Devices - Display or produce results of the computer’s processing (e.g., monitors,
printers).
How does the Software Work with Hardware?
When you give input (e.g., typing a letter on a keyboard), the hardware (keyboard) sends
this input to the software. The software then converts the input into a machine-readable
language (binary) that the CPU can process. The output (e.g., the letter ‘A’) is then
displayed on the screen as a result of this process.
Example Process:
1. You press the Shift key and the A key on your keyboard.
2. The software translates this into machine code and tells the CPU that the letter ‘A’ should
be displayed.
3. The CPU processes the input, and the monitor shows the letter 'A'.
Types of Computers
Computers can be categorized in various ways based on size, processing power,
functionality, and other parameters. Here's an overview of the different types:
1. Types of Computers Based on Size
Microcomputers: Microcomputers are meant for individual use. They are small,
compact and very small. For example smartphones and desktops.
Minicomputers: They are used in businesses that are mid-sized and are more powerful
than microcomputers. Servers are an example of minicomputers.
Mainframe computers: These are used by large organizations. They help in the
processing of bulk data.
Supercomputers: These are extremely powerful computers that help in carrying out
complex calculations. They aren't meant for personal use and are often used for research
purposes.
2. Types of Computers Based on Processing Power
Personal computers (PCs): These are the most common type of computer and are
designed for personal use. PCs include desktops, laptops, and tablets.
Servers: Servers are designed to manage and distribute resources and data to multiple
users or devices. They are often used in businesses or organizations to store and share
data and run applications.
Mainframes: Mainframe computers are large, powerful machines that are designed to
handle massive amounts of data and perform complex operations. They are often used in
large corporations or government agencies.
Supercomputers: Supercomputers are extremely powerful computers that are designed
to process data at extremely high speeds. They are often used for scientific research and
other specialized applications.
Embedded systems: Embedded systems are small computers that are built into other
devices, such as appliances, cars, and medical devices. They are designed to perform
specific functions and operate without human intervention.
Wearable computers: Wearable computers are small, portable devices that are worn on
the body, such as smartwatches or fitness trackers. They are designed to track data and
provide information on the go.
3. Types of Computers Based on Functionality
Analog computers: In analog computers data is stored using continuous physical
quantities. A mechanical integrator is an example of an analogue computer.
Digital computers: These are the most common types of computers found in the market
today. Data is processed in digital computers using discrete values. Smartphone is a
common example of digital computers.
Hybrid computers: These are a combination of both analogue and digital computers.
Examples include complex medical equipment.
Issues in Computer Design
Computers involve many components that have their own speed, size and power
consumption requirements. There are different operating systems that use these
computers. Due to different kind of software, the following issues arise in design.
Performance
Maximizing processing speed, memory speed, and I/O performance.
Designing energy-efficient systems for reducing environmental impact and improving
battery life.
Processors operate much faster than memory and IO devices, creating a bottleneck that
can significantly slow down the overall system.
Security
Protecting sensitive data from unauthorized access and breaches through robust
encryption and authentication.
Compatibility and User Experience
Ensuring that systems run seamlessly across various operating systems and hardware
configurations.
Designing systems that are intuitive and easy for users to operate.
System Architecture and Infrastructure
Building fault tolerant systems that can withstand and recover from failures without
significant downtime.
Modern systems are highly complex, requiring careful management of design,
optimization, and integration to avoid excessive costs and development time.
Resource and Technical Constraints
It must work within the constraints of physical limitations, acknowledging that both
computer speed and memory capacity are finite.
Effective techniques are needed to manage memory usage, especially when dealing with
large applications or datasets, to prevent slowdowns and crashes.
Difference between Von Neumann Architecture and Harvard Architecture
Feature Von Neumann Harvard Architecture
Architecture
Memory Single memory for data Separate memory for data
and instructions and instructions
Buses Single bus for data & Separate buses for data and
instructions instructions
Speed Slower (bottleneck occurs) Faster (parallel access
possible)
Complexity Simple design Complex design
Cost Low cost Higher cost
Performance Limited due to single High performance
pathway
Bottleneck Suffers from Von Neumann No bottleneck
bottleneck
Parallelism Cannot fetch data & Can fetch both
instruction together simultaneously
Usage General-purpose computers Embedded systems,
microcontrollers
Key Concept Difference (Very Important)
Von Neumann → One memory + one bus
Harvard → Separate memory + separate buses
Von Neumann Bottleneck
Occurs because data and instructions share the same bus
CPU must wait → reduces speed
Examples
Von Neumann Architecture:
Desktop computers, laptops
Harvard Architecture:
Microcontrollers (8051), DSP processors
Summary:
Von Neumann architecture uses a single memory and bus for data and instructions, whereas
Harvard architecture uses separate memory and buses, resulting in higher performance.
[Link] Elements of Machine Language
The basic elements of machine language, the computer's native binary code (0s and 1s),
include Opcodes (operation codes for actions like add/subtract), Operands (data or memory
locations for the operation), and Addressing Modes (rules for finding operands), all structured
into binary instructions that the CPU executes directly, often using internal registers for quick
data storage and manipulation.
Core Components
Binary Digits (Bits): The fundamental 0s and 1s that form all machine code.
Opcodes (Operation Codes): Specific bit patterns representing CPU actions (e.g., ADD,
LOAD, STORE).
Operands: The data or addresses that the opcode acts upon, telling the CPU where the
data is.
Supporting Elements
Registers: Tiny, fast storage units inside the CPU used to hold data during processing.
Memory Addresses: Locations in main memory used to fetch or store data for
instructions.
Addressing Modes: Different ways to specify operand locations (e.g., directly in a
register, at a memory address).
Instruction Format: The specific layout of bits for instruction, varying by CPU
architecture (e.g., RISC-V, ARM).
How They Work Together
Machine language instruction combines an opcode (e.g., "Add") with operands (e.g.,
locations of two numbers in registers or memory) to form a complete, executable command,
like 01100110 00001010, telling the CPU to add two values.
Machine language is the lowest-level programming language directly communicating
with a computer’s central processing unit (CPU). Comprising binary code—sequences of zeros
and ones—machine language is the most basic form of programming, representing instructions
that computers can execute directly. It serves as the foundation for all higher-level programming
languages and is essential for understanding how computers process and execute commands at
the hardware level.
Components of Machine Language
Machine code is the lowest-level programming language that computers understand
directly. It consists of instructions executed by the central processing unit (CPU). The following
are the components:
Opcode (Operation Code): Represents the actual operation or command to be executed
by the CPU. Specifies the fundamental functions such as addition, subtraction, loading
data into registers, or branching.
Operand: Represents the data or the memory address on which the operation will be
performed. Instructs the CPU about the location or value involved in the process
Memory Addresses: Indicate locations where data or instructions are stored in
the computer’s memory. Machine language instructions often include memory
addresses to fetch or store data.
Registers: Small, fast storage locations within the CPU. Some machine language
instructions operate directly on data stored in registers for quick access.
Machine Instructions: Binary representations of the instructions that the CPU can
execute. They are typically written in hexadecimal or binary notation.
Control Signals: Signals that control the internal operations of the CPU. Govern
activities such as reading from or writing to memory, performing arithmetic or logic
operations, and transferring data.
Condition Codes/Flags: Status indicators that reflect the outcome of operations. Flags
like zero flag, carry flag, and overflow flag are set or cleared based on the result of
arithmetic or logical operations.
Machine Language Program: A sequence of machine language instructions forms a
program. Represents the set of actions a computer should take to accomplish a specific
task.
Understanding and working with these components requires a deep understanding of the
computer’s architecture and instruction set. While it is challenging for humans to read and write
directly, it is the foundation for higher-level programming languages. It is essential for
understanding the inner workings of computers.
Examples
Machine language instructions are typically represented in binary or hexadecimal
notation. Here’s a simplified example of machine language instructions for hypothetical
computer architecture.
In this example-
LOAD R1, 0x1234 loads the value at memory address 0x1234 into register R1.
ADD R2, R1 adds the content of register R1 to R2.
STORE R2, 0x5678 stores the value in register R2 at memory address 0x5678.
SUB R1, R2 subtracts the content of register R2 from R1.
JUMP 0x00 is an unconditional jump instruction, causing the program to jump back to
the beginning at memory address 0x00.
Difference Between Machine Language and Assembly Language
Feature Machine Language Assembly Language
Representation Consists of binary code (0s and Uses mnemonics and symbols for
1s). commands.
Readability Not human-readable; raw binary More human-readable due to
format. mnemonics.
Abstraction Level Lowest-level programming An intermediate level between
language. machine code and high-level
languages.
Programming Tedious and error-prone for Easier for programmers to read and
humans. write.
Translation They are executed directly by the Requires an assembler for conversion
CPU. to machine code.
Efficiency It is more efficient for the Slightly less efficient due to
computer to execute. translation overhead.
Usage Rarely used directly by It is still used in embedded systems
programmers today. and low-level programming tasks.
Machine Language in Artificial Intelligence
Machine language is a cornerstone in artificial intelligence (AI), serving as the foundational
communication interface for computers to understand and execute instructions. It enables the
intricate implementation of algorithms and neural networks, offering essential low-level
instructions for the CPU to handle complex computations in AI development.
Whether involved in training machine learning models, processing extensive datasets, or
executing decision-making algorithms, machine language acts as the crucial link between the
high-level abstractions of AI frameworks and the hardware-level operations of computers. As AI
progresses, the efficiency achieved through machine language remains indispensable for
unlocking the full potential of AI applications.
Algorithm Implementation: Machine language is essential for implementing complex
algorithms in artificial intelligence, providing low-level instructions for efficiently
executing mathematical and logical operations.
Neural Network Execution: It plays a crucial role in executing the operations within
artificial neural networks, foundational in many AI models.
Optimization for Performance: Machine language allows for fine-grained control over
hardware resources, optimizing AI algorithms for enhanced performance, particularly on
specialized hardware like GPUs(Graphics Processing Units) and TPUs(Tensor Processing
Units).
Real-time Processing: For applications requiring real-time processing, such as
autonomous systems, machine language ensures rapid and efficient execution of AI
models.
Embedded Systems in AI: Machine language is vital for developing AI applications in
embedded systems, contributing to deploying intelligent features in devices like IoT
devices and edge computing devices.
Hardware Acceleration: Leveraging machine language, programmers can optimize AI
computations for hardware accelerators like GPUs and FPGAs, boosting the speed and
efficiency of AI tasks, especially in deep learning applications.
[Link] Machine Language
HACK Machine Language is the low-level programming language(machine-
level language) used by the HACK computer (from Nand2Tetris).
It consists of binary instructions (0s and 1s) that the computer hardware( HACK CPU)
can execute directly. Each instruction is 16 bits long.
Key Features of HACK Machine Language
Binary language (16-bit instructions)
Executed directly by hardware
No variables, loops, or functions
Works closely with CPU registers and memory
Registers in HACK Computer
A Register – stores address or value
D Register – stores data
Memory (RAM) – stores data and instructions
M → memory location pointed by A register
Example Program (HACK Machine Language)
Add two numbers:
@2
D=A
@3
D=D+A
@0
M=D
👉 Adds 2 and 3, stores result in memory location 0
Types of Instructions in HACK Machine Language
HACK machine language has two instruction types:
Types of Instructions (Only 2)
1. A–Instruction (Address Instruction)
Format:
0vvvvvvvvvvvvvvv
First bit = 0
Remaining 15 bits represent a value or memory address
Purpose:
Load a value into the A register
Access memory location
Example :
@21
Binary: 0000000000010101
👉 Loads value 21 into A register
Example 2
A–Instruction
Purpose: Load a value or address into A register
Format:
0vvvvvvvvvvvvvvv
Example:
@5
Binary:
0000000000000101
👉A=5
2️⃣ C–Instruction (Compute Instruction)
Purpose: Calculation, data storage, jump
Format:
111 a c1 c2 c3 c4 c5 c6 d1 d2 d3 j1 j2 j3
Parts:
comp → computation to be done (calculation)
dest → where to store result
jump → decision making (condition for jump
Example 1:
D=A+1
👉 Adds 1 to A and stores in D
Example 2:
D=D+A
Binary representation executes addition and stores result in D register
Simple Program Example
Add two numbers (2 + 3):
@2
D=A
@3
D=D+A
@0
M=D
Explanation:
@2 → A = 2
D=A → D = 2
@3 → A = 3
D=D+A → D = 5
@0 → A = 0
M=D → RAM[0] = 5
Advantages
Very fast execution
Direct control over hardware
Simple instruction set
Disadvantages
Difficult to write and debug
Not human-friendly
Error-prone
Summary:
HACK machine language is a low-level binary language consisting of 16-bit A and C
instructions, used to directly control registers and memory of the HACK computer.
4. Different sets of instructions
Basic computer instructions are commands given to a computer to perform specific tasks.
These instructions are typically divided into three categories:
1. Data Transfer Instructions: Move data between memory and registers (e.g., Load,
Store).
2. Arithmetic and Logic Instructions: Perform math or logic operations (e.g., Add,
Subtract, AND, OR).
3. Control Instructions: Guide the flow of the program (e.g., Jump, Branch, Call).
Data Transfer Instructions
These instructions deal with moving data from one location to another within the computer.
Think of it as copying or transferring information between various components like memory,
registers, or storage.
Common Data Transfer Instructions:
Load: Copies data from memory to a register (temporary storage inside the CPU).
Store: Transfers data from a register to memory.
Move: Transfers data from one register to another.
Arithmetic and Logic Instructions
These instructions are used to perform mathematical and logical operations. They enable
computers to handle calculations and make decisions based on certain conditions.
Arithmetic Instructions:
Add: Adds two numbers.
Subtract: Subtracts one number from another.
Multiply: Multiplies two numbers.
Divide: Divides one number by another.
Logic Instructions:
AND: Compares two bits and returns 1 if both are 1; otherwise, returns 0.
OR: Compares two bits and returns 1 if at least one is 1.
NOT: Inverts a bit (1 becomes 0, and 0 becomes 1).
XOR (Exclusive OR): Returns 1 if the bits are different, 0 if they are the same.
Control Instructions
Control instructions determine the flow of execution in a program. They guide the computer
on which instruction to execute next, allowing flexibility in decision-making and repeated
actions.
Common Control Instructions:
Jump (JMP): Directs the program to execute a specific instruction elsewhere in the code.
Conditional Branch: Jumps to another instruction only if a specific condition is
true. Example: Branch if zero (BZ) or branch if not zero (BNZ).
Call: Transfers control to a subroutine (a set of instructions performing a specific task)
and returns afterward.
Return: Brings back control to the main program after a subroutine is executed.
Other Instructions:
Instruction Set of a Basic Computer
The basic computer has 16-bit instruction register (IR) which can denote either memory
reference or register reference or input-output instruction.
Memory Reference Instructions
These instructions refer to memory address as an operand. The other operand is always
accumulator. Specifies 12-bit address, 3-bit opcode (other than 111) and 1-bit addressing
mode for direct and indirect addressing.
Computer organization refers to the way in which the components of a computer system
are organized and interconnected to perform specific tasks. One of the most fundamental
aspects of computer organization is the set of basic computer instructions that the system
can execute.
5. Hack programming:
Hack was introduced on March 20, 2014. Before the announcement of the new language,
Facebook had already implemented the code and tested it on a large part of its web site.
Hack is a programming language for the HipHop Virtual Machine (HHVM), created
by Meta (formerly Facebook) as a dialect of PHP. The language implementation is free
and open-source software, licensed under an MIT License.
Hack is designed to interoperate seamlessly with PHP, which is a widely used open-
source scripting language that has a focus on web development and can be embedded
into HTML. A majority of valid PHP scripts are also valid in Hack; however, many less-
often used PHP features and language constructs are unsupported in Hack.
Hack allows use of both dynamic typing and static typing. This kind of a type system is
called gradual typing, which is also implemented in other programming languages such
as ActionScript.[5] Hack's type system allows types to be specified for function arguments,
function return values, and class properties; however, types of local variables are always
inferred and cannot be specified.
Key Aspects of Hack Programming
Hack Assembly Language: A simple, low-level language with two main instruction
types:
o A-command (@value): Sets the A-register to a memory address or constant.
o C-command (dest = comp; jump): Performs computations, stores results (dest),
and optionally jumps (jump) based on conditions.
The Hack Computer: A virtual computer built from logic gates (ALU, RAM, CPU) that
executes Hack machine code, with memory-mapped I/O for screen and keyboard.
Gradual Development: Students first build the hardware (CPU, RAM) and then program
it using assembly, eventually building an assembler and virtual machine to run higher-
level languages.
Focus: The goal is understanding how computers work at their core, not malicious
hacking or using the PHP-based Hack language (also called Hack) used by Meta for web
development.
Example Hack Code (Simplified)
@10 // Load the value 10 into the A-register.
D=M // Copy the value from RAM[A] (which is 10) into the D-register.
@20 // Load the value 20 into the A-register.
D=D+M // Add the D-register (10) and RAM[A] (20), store in D (result 30).
@output // Set A to the address of 'output'.
M=D // Store the result (30) into RAM[output].
In essence, it's "programming for the Hack computer," teaching fundamental computing
principles through hands-on construction and low-level coding.
Syntax and semantics
The basic file structure of a Hack script is similar to a PHP script with a few changes. A
Hack file does not include the <?php opening markup tag and forbids using top-level
declarations.[11] Code must be placed in an entrypoint function. These are automatically
executed if they are in the top-level file, but not if the file is included via include, require,
or the autoloader. Like other functions in Hack, the function names must be unique within
a project – i.e., projects with multiple entrypoints can not both be called main:
<<__EntryPoint>>
function main(): void {
echo 'Hello, World!';
}
The above script, similar to PHP, will be executed and the following output is sent to the
browser:
Hello, World!
Unlike PHP, Hack and HTML code do not mix; either XHP or another template
engine needs to be used.[8]
Functions
Like PHP 7, Hack allows types to be specified for function arguments and function return
values. Functions in Hack are thus annotated with types like the following:
// Hack functions are annotated with types.
function negate(bool $x): bool {
return !$x;
}
6. Assembly language vs Machine language
Machine Language
Machine language is the lowest-level programming language that is directly understood by
the computer hardware.
Features:
Written in binary (0s and 1s)
Executed directly by CPU
No translator required
Hardware dependent
Very fast execution
Example:
10110000 01100001
Advantages:
Executes very fast
No need for compiler or assembler
Disadvantages:
Very difficult to write and understand
Error-prone
Hard to debug and maintain
Assembly Language
Assembly language is the more than low level and less than high-level language, so it is
intermediary language. Assembly languages use numbers, symbols, and abbreviations instead of
0s and [Link] example: For addition, subtraction and multiplications it uses symbols likes Add,
sub and Mul, etc.
Features:
Uses symbols and mnemonics
Assembler converts it into machine language
Easier than machine language
Hardware dependent
One-to-one correspondence with machine instructions
Example:
MOV A, 61H
Advantages:
Easier to read and write than machine language
Easier debugging
Efficient use of hardware resources
Disadvantages:
Requires an assembler
Machine dependent
Still complex compared to high-level languages
Below is a table of differences between Machine Language and Assembly Language:
Machine Language Assembly Language
Machine language is only understood by Assembly language is only understood by
the computers. human beings not by the computers.
In machine language data only represented In assembly language data can be
with the help of binary format(0s and 1s), represented with the help of mnemonics
hexadecimal and octa decimal. such as Mov, Add, Sub, End etc.
Machine language is very difficult to Assembly language is easy to understand
understand by the human beings. by the human being as compared to
machine language.
Modifications and error fixing cannot be Modifications and error fixing can be done
done in machine language. in assembly language.
Machine language is very difficult to Easy to memorize the assembly language
memorize so it is not possible to learn the because some alphabets and mnemonics
machine language. are used.
Execution is fast in machine language Execution is slow compared to machine
because all data is already present in binary language.
format.
There is no need for a translator. The Assembler is used as translator to convert
machine understandable form is the mnemonics into machine understandable
machine language. form.
Machine language is hardware dependent. Assembly language is machine dependent,
and it is not portable.
7. Assembler- assembly process
An assembler is a program that translates assembly language (human-readable mnemonics)
into machine code (binary for CPUs) during the assembly process, which involves two main
phases: Analysis (building a symbol table, allocating memory with Location Counter)
and Synthesis (converting instructions to binary, handling directives like DB , DW , and
generating an object file), ultimately preparing code for linking and execution.
The Assembler (The Program)
Function: Translates symbolic assembly code (like MOV AX, 10) into numerical
machine code (e.g., B8 0A 00).
Key Task: Replaces mnemonics with opcodes, resolves symbolic names (labels) for
memory locations, and handles assembler directives (instructions for the assembler
itself).
Types: Can be single-pass (one scan) or multi-pass (multiple scans).
The Assembly Process (The Steps)
1. Input: The assembler takes the assembly source code file (e.g., .asm).
2. Analysis Phase (Pass 1):
1. Scans the code to identify symbolic names (labels, variables).
2. Uses a Location Counter (LC) to assign memory addresses to these symbols.
3. Builds a Symbol Table to store these symbol-address pairs.
3. Synthesis Phase (Pass 2):
1. Converts mnemonics (like ADD) to their machine code opcodes.
2. Replaces symbolic references with their actual memory addresses from the
symbol table.
3. Processes directives (e.g., .DATA, DB for Define Byte) to allocate memory for
data.
4. Produces an Object File, containing machine code and linking information.
4. Linking & Loading:
The object file is then passed to a Linker, which combines it with libraries and other
object files to create an Executable File, which is then loaded into memory and run.
Key Concepts
Mnemonics: Short, symbolic names for instructions (e.g., ADD, MOV).
Directives: Instructions for the assembler, not the CPU (e.g., DB, EQU).
Object Code: The output of the assembler, in binary format, ready for linking.
VIII. Hack assembly language
Hack assembly language is the low-level symbolic language used for the Hack computer, a
16-bit computer architecture designed for the "Nand to Tetris" course (The Elements of
Computing Systems). It is a minimalist Instruction Set Architecture (ISA) that is surprisingly
powerful despite having only two types of instructions.
1. The Architecture Basics
To understand the assembly, you have to understand the hardware it talks to:
Registers: There are only two main 16-bit registers:
o A-register (Address): Holds either a data value or a memory address.
o D-register (Data): Strictly used for storing data values.
Memory (M): Refers to the RAM word currently pointed to by the A-register. If A=512,
then M refers to RAM[512].
2. The Instruction Set
There are only two types of instructions in Hack assembly:
A-Instructions (Address)
Syntax: @value
Used to load a constant or a memory address into the A-register.
Example: @10 sets the A-register to 10.
Use case: To prepare for a jump or to select a specific RAM location.
C-Instructions (Compute)
Syntax: dest = comp ; jump
This is the workhorse of the language. It tells the computer what to calculate, where to save
it, and what to do next.
comp: The operation (e.g., D+1, D-A, 0, !M).
dest: Where to store the result (M, D, A, or combinations like MD).
jump: Condition for jumping to the ROM address in the A-register (JGT, JEQ, JMP,
etc.).
3. Common Code Patterns
Setting a Variable
To perform RAM[10] = 5:
Code snippet
@5 // Load value 5 into A
D=A // Move it to D (because we need A to point to the address)
@10 // Load address 10 into A
M=D // RAM[10] = D (which is 5)
Simple Addition
To perform RAM[2] = RAM[0] + RAM[1]:
Code snippet
@0
D=M // D = RAM[0]
@1
D=D+M // D = D + RAM[1]
@2
M=D // RAM[2] = D
Infinite Loop (Termination)
Since Hack programs run on hardware, they don't "exit." You usually end them with an
infinite loop to prevent the CPU from executing random memory:
Code snippet
(END) // A label
@END
0;JMP // Unconditional jump to END
4. Symbols and Memory Mapping
Hack uses built-in symbols to make programming easier:
R0-R15: Virtual registers mapping to RAM[0] through RAM[15].
SCREEN: Maps to @16384, the start of the display memory.
KBD: Maps to @24576, the keyboard interface.
Comparison of Jump Conditions
Mnemonic Effect
JGT Jump if out > 0
JEQ Jump if out = 0
JGE Jump if out >= 0
JLT Jump if out < 0
JNE Jump if out != 0
JMP Unconditional Jump
9. Assembly language to binary conversions
In the Hack architecture, converting assembly to binary (machine code) is a mechanical
process of translating mnemonics into a 16-bit bitmask. Every line of assembly code
corresponds to exactly one 16-bit binary instruction.
1. A-Instruction Conversion
Format: @value
This is the simplest conversion. An A-instruction always starts with a 0. The remaining
15 bits are the binary representation of the decimal value.
Assembly: @21
Binary Process:
1. First bit is 0.
2. Convert 21 to 15-bit binary: 000000000010101.
Result: 0000000000101010
2. C-Instruction Conversion
Format: dest = comp ; jump
A C-instruction is always 16 bits long and follows this specific template:
1 1 1 a c1 c2 c3 c4 c5 c6 d1 d2 d3 j1 j2 j3
This is HACK machine language (from Nand2Tetris).
I’ll explain each bit clearly, step-by-step, in an easy way 👍
C-Instruction Format (16 bits)
dest = comp ; jump
Binary format:
1 1 1 a c1 c2 c3 c4 c5 c6 d1 d2 d3 j1 j2 j3
111 — Instruction Type
First 3 bits are always 111
This tells the CPU “This is a C-instruction”
a c1 c2 c3 c4 c5 c6 — COMP field (7 bits)
These bits specify what computation to perform
a bit
a = 0 → computation uses A register
a = 1 → computation uses Memory M (M = RAM[A])
Example:
D=A → a=0
D=M → a=1
c1 c2 c3 c4 c5 c6
These 6 bits select the ALU operation
Examples:
Computation a c1 c2 c3 c4 c5 c6
0 01 0 1 0 1 0
1 01 1 1 1 1 1
-1 01 1 1 0 1 0
D 00 0 1 1 0 0
Computation a c1 c2 c3 c4 c5 c6
A 01 1 0 0 0 0
M 11 1 0 0 0 0
D+1 00 1 1 1 1 1
D+A 00 0 0 0 1 0
D+M 10 0 0 0 1 0
D-A 00 1 0 0 1 1
D-M 10 1 0 0 1 1
📌 a changes A → M, rest bits stay same.
d1 d2 d3 — DEST field (3 bits)
Specifies where to store the result
d1 d2 d3 Destination
0 0 0 None
1 0 0 A
0 1 0 D
0 0 1 M
1 1 0 AD
1 0 1 AM
0 1 1 DM
1 1 1 ADM
Example:
D=A → 010
M=D → 001
AD=D+1 → 110
j1 j2 j3 — JUMP field (3 bits)
Specifies when to jump
j1 j2 j3 Jump Condition
0 0 0 No jump
0 0 1 JGT ( > 0 )
0 1 0 JEQ ( = 0 )
0 1 1 JGE ( ≥ 0 )
j1 j2 j3 Jump Condition
1 0 0 JLT ( < 0 )
1 0 1 JNE ( ≠ 0 )
1 1 0 JLE ( ≤ 0 )
1 1 1 JMP ( always )
👉 Example:
D;JGT → 001
0;JMP → 111
Example ConversionInstruction:
D = M + 1 ; JGT
Binary:
111 1 110111 010 001
✔ a=1 (uses M)
✔ comp = M+1 → 110111
✔ dest = D → 010
✔ jump = JGT → 001
Summary
Field Meaning
a A or M selector
c1–c6 ALU operation
d1–d3 Destination
j1–j3 Jump condition
Header (3 bits): Always 111.
Comp (7 bits): The a bit + 6 c bits. The a bit is 0 if using register A and 1 if using
memory M.
Dest (3 bits): Where to store the result (A, D, M).
Jump (3 bits): The condition for jumping (JGT, JEQ, etc.).
Example: D = D + M
To convert D = D + M (with no jump):
1. Header: 111
2. Comp (D+M): Look up D+M in the specification table. The a bit is 1 (because of M),
and the c bits for D+M are 000010. Total comp: 1000010.
3. Dest (D): The code for storing into D only is 010.
4. Jump (null): No jump is specified, so the code is 000.
Final Binary: 1111 0000 1001 0000
3. Translation Table Reference
To assemble a C-instruction manually, you use these standard lookup values:
Field Mnemonic Binary Code
Dest M 001
D 010
MD 011
Jump JGT (out > 0) 001
JEQ (out = 0) 010
JMP (always) 111
4. The Role of the Assembler
While you can do this by hand, a software Assembler automates it in two passes:
1. First Pass: It finds all labels like (LOOP) and maps them to the ROM address where they
appear.
2. Second Pass: It translates every line into binary, replacing labels and variables with their
actual numeric addresses.