Microprocessor And Computer ArchitectureUnit 514 min read
Arithmetic & Logic Operations: ALU, Flags, Binary Math, Shifts, Rotates
Unit 5 of Microprocessor And Computer Architecture covers the core arithmetic and logic unit (ALU) operations, binary arithmetic (addition, subtraction, multiplication, division), logic gates and operations, bitwise shifts/rotates, and how flags (zero, carry, overflow) affect results. Includes real-world examples from
TAKEAWAYS:
- The ALU performs arithmetic (add/subtract) and logic (AND/OR/XOR) operations on binary data, with results stored in registers or memory.
- Binary arithmetic follows two’s complement rules for signed numbers, and floating-point operations use IEEE 754 standards for precision.
- Shift operations (logical/arithmetic) and rotate operations manipulate bits for multiplication/division or data alignment.
- Flags (ZF, CF, OF, SF) indicate operation outcomes (zero, carry, overflow, sign) and are critical for conditional branching.
- Logic gates (AND, OR, NOT, XOR) implement Boolean algebra in hardware, forming the basis of combinational circuits.
- Pipelining in ALU operations improves throughput by overlapping instruction execution stages (fetch, decode, execute).
Core Concepts: ALU and Flags
The Arithmetic Logic Unit (ALU) is the heart of the microprocessor, executing all arithmetic and logic operations. It takes operands from registers or memory, processes them, and stores the result back to a destination register or memory location.
ALU Operations
The ALU performs two broad categories of operations:
- Arithmetic Operations:
- Addition (
ADD), Subtraction (SUB), Increment (INC), Decrement (DEC), Multiplication (MUL), Division (DIV). - Example:
ADD B, Cadds the contents of registerBandC, storing the result inB.
- Addition (
- Logic Operations:
- AND, OR, XOR, NOT, Compare (
CMP), Test (TEST).
- AND, OR, XOR, NOT, Compare (
Flags Register
The ALU sets status flags after operations to reflect the result’s state. These flags are used by conditional instructions (e.g., JZ, JC) to alter program flow.
Flags Explained:
| Flag | Name | Set When |
|---|---|---|
| ZF | Zero Flag | Result is zero. |
| CF | Carry Flag | Unsigned overflow (carry out/borrow in). |
| OF | Overflow Flag | Signed overflow (e.g., 127 + 1 in 8-bit signed arithmetic). |
| SF | Sign Flag | Result is negative (MSB = 1). |
| AF | Auxiliary Flag | Half-carry in BCD operations (rarely used in modern processors). |
Binary Arithmetic Operations
Binary arithmetic follows strict rules, especially for signed numbers (two’s complement) and floating-point numbers (IEEE 754).
1. Addition and Subtraction
Unsigned Addition:
- Example:
1010 (10) + 0110 (6) = 10000 (16). - If the result exceeds the bit width, the Carry Flag (CF) is set.
- Example:
Signed Addition (Two’s Complement):
- Example:
0111 (-1) + 0001 (1) = 0000 (0). - Overflow occurs if the sign of the result differs from the signs of the operands (e.g.,
0111 + 0111 = 1110→ OF is set).
- Example:
Worked Example: Bank Loan Interest Calculation (Real-World Tie-In) A bank calculates monthly interest on a loan using floating-point addition. Suppose:
- Principal =
100,000(stored as0x42C80000in IEEE 754 single-precision). - Interest rate =
0.05(stored as0x3E666666). - The ALU computes:
The microprocessor performs:Interest = Principal × Rate = 100,000 × 0.05 = 5,000- Floating-point multiplication (ALU handles exponent/mantissa separately).
- Rounds the result to the nearest representable value.
- Stores it back to memory.
2. Multiplication and Division
Multiplication:
- Hardware multipliers use shift-and-add or array multipliers.
- Example:
1010 (10) × 0110 (6) = 01100100 (60). - Flags affected: ZF (if result is zero), CF (if overflow).
Division:
- Uses shift-and-subtract or array dividers.
- Example:
1100 (12) ÷ 0110 (6) = 0010 (2)with remainder0000 (0). - Flags affected: ZF (if remainder is zero), CF (if division by zero).
Logic Operations
Logic operations manipulate bits using Boolean algebra. The ALU implements these via combinational circuits (AND, OR, NOT, XOR gates).
Logic Gates in ALU
| Gate | Symbol | Truth Table | ALU Operation Example |
|---|---|---|---|
| AND | & |
0 & 0 = 0, 1 & 1 = 1 |
AND B, C (bitwise AND) |
| OR | ` | ` | `0 |
| NOT | ~ |
~0 = 1, ~1 = 0 |
NOT B (bitwise NOT) |
| XOR | ^ |
0 ^ 1 = 1, 1 ^ 1 = 0 |
XOR B, C (bitwise XOR) |
Worked Example: eSewa Transaction Validation eSewa uses XOR operations to validate transaction hashes:
- The sender’s phone computes
Hash = XOR(Amount, SecretKey). - The server verifies the hash by recomputing
XOR(Amount, SecretKey)and comparing it to the received hash.- If
Hash == ReceivedHash, the transaction is valid (ZF is set). - If not, the transaction is rejected (ZF is cleared).
- If
Shift and Rotate Operations
These operations move bits within a register or memory location, often used for multiplication/division or data alignment.
1. Shift Operations
| Operation | Description | Example (Register B = 1011) |
Flags Affected |
|---|---|---|---|
| Logical Shift Left (SAL/SHL) | Shifts bits left; MSB lost, LSB filled with 0. | 1011 → 0110 (×2) |
CF = MSB |
| Logical Shift Right (SAR/SHR) | Shifts bits right; LSB lost, MSB filled with 0. | 1011 → 0101 (÷2) |
CF = LSB |
| Arithmetic Shift Right (ASR) | Shifts right; preserves sign bit (MSB). | 1101 → 1110 (signed ÷2) |
CF = LSB |
| Rotate Left (ROL) | Shifts left; MSB wraps to LSB. | 1011 → 0111 (with CF=1) |
CF = MSB |
| Rotate Right (ROR) | Shifts right; LSB wraps to MSB. | 1011 → 1101 (with CF=1) |
CF = LSB |
Worked Example: Pathao Route Optimization (Real-World Tie-In) Pathao uses bit shifting to optimize route calculations:
- A 16-bit integer represents distance in meters (e.g.,
0x03E8 = 1000meters). - To convert to kilometers (÷1000), the ALU performs:
MOV AX, 0x03E8 ; Load distance (1000 meters) SAR AX, 10 ; Arithmetic shift right by 10 (÷1024 ≈ ÷1000)- This approximates the division without a full
DIVinstruction, saving cycles.
- This approximates the division without a full
2. Comparison Table: Shift vs. Rotate
| Feature | Shift Operations | Rotate Operations |
|---|---|---|
| Bit Loss | Bits are lost (filled with 0 or sign bit). | Bits wrap around (circular shift). |
| Use Case | Multiplication/division, alignment. | Circular buffers, cryptography. |
| Flags | CF = lost bit. | CF = last bit shifted out. |
| Example | SHL AX, 1 (multiply by 2). |
ROR BL, 1 (rotate right). |
Floating-Point Arithmetic
Floating-point numbers use the IEEE 754 standard, which defines:
- Single-precision (32-bit): 1 sign bit, 8 exponent bits, 23 mantissa bits.
- Double-precision (64-bit): 1 sign bit, 11 exponent bits, 52 mantissa bits.
Floating-Point Addition Pipeline
- Align Exponents: Shift the mantissa of the smaller exponent to match the larger.
- Add Mantissas: Perform binary addition on the aligned mantissas.
- Normalize: Adjust the result to standard form (1.xxxx × 2^exponent).
- Round: Truncate or round to fit the mantissa size.
- Check Flags: Set flags for overflow/underflow.
Mermaid Diagram: Floating-Point Addition Pipeline
Worked Example: YouTube Video Buffering YouTube uses floating-point arithmetic to:
- Calculate buffering time based on bitrate and network speed.
- Example: Buffer =
VideoSize / NetworkSpeed. - If
VideoSize = 10,000,000 bytesandNetworkSpeed = 2,000,000 bytes/sec, the ALU computes:BufferTime = 10,000,000 / 2,000,000 = 5.0 seconds
- Example: Buffer =
- The result is stored as a floating-point value (
0x40A00000in IEEE 754).
## In the Real World
eSewa (Transaction Validation)
- Idea Used: XOR operations and flags (ZF).
- How: eSewa computes a checksum using
XORon transaction details (amount, timestamp, secret key). The server verifies the checksum by recomputing the XOR and comparing it to the received value. IfZFis set (checksums match), the transaction proceeds; otherwise, it’s flagged as fraudulent.
Pathao (Route Optimization)
- Idea Used: Arithmetic shift (ASR) and binary multiplication.
- How: Pathao’s algorithm converts distances from meters to kilometers using
ASR(shift right by 10 for ÷1024 ≈ ÷1000). It also uses bitwise operations to encode/decode route coordinates efficiently, reducing computation time.
Nepal Rastra Bank (Loan Interest Calculation)
- Idea Used: Floating-point arithmetic and overflow flags (OF).
- How: Banks use the ALU’s floating-point unit to calculate monthly interest on loans. For example, a loan of
5,000,000at8%annual interest:- Monthly interest =
5,000,000 × (8/12)/100 = 33,333.33. - The ALU handles the multiplication and rounding, while
OFensures no overflow occurs during large-scale calculations.
- Monthly interest =
NTC (Network Traffic Routing)
- Idea Used: Bitwise AND/OR for IP address matching.
- How: Routers use bitwise operations to match IP prefixes. For example, to check if an IP
192.168.1.5belongs to the subnet192.168.1.0/24:AND AX, 0xFFFFFF00 ; Mask the last 8 bits CMP AX, 0xC0A80100 ; Compare with subnet- The
ANDoperation isolates the network portion, andCMPsets flags for routing decisions.
- The
## Exam Tip
This unit is heavily tested on:
Definitions and Differences:
- Always distinguish between logical shift (SHL/SHR) and arithmetic shift (ASR).
- Explain when CF vs. OF is set in addition/subtraction.
- Example question: "Differentiate between shift right and arithmetic shift right operation." → Answer: Shift right fills with 0; arithmetic shift right preserves the sign bit.
Worked Examples:
- Must-practice: Binary addition/subtraction with flags, floating-point addition pipeline, shift/rotate operations.
- Example question: "Illustrate and explain arithmetic pipeline for addition of two floating-point binary numbers." → Draw the 5-step pipeline (align, add, normalize, round, check flags) and show a numerical example.
Real-World Applications:
- Link concepts to banking (interest), e-commerce (hashing), or routing (bitwise operations).
- Example question: "How does Pathao use bitwise operations for route optimization?" → Answer: Uses
ASRfor distance conversion andANDfor IP subnet matching.
Assembly-Level Operations:
- Know microoperations for stack operations (e.g.,
POPin 8085):POP B:SP ← SP + 1; B ← M[SP](whereMis memory).
- Example question: "Write down microoperations for POP operation in register stack." → Answer: Increment stack pointer, load register from memory.
- Know microoperations for stack operations (e.g.,
Flag Analysis:
- For any arithmetic/logic operation, predict all affected flags.
- Example:
SUB B, CwhereB = 0x05,C = 0x07:- Result =
0xFF(overflow),ZF = 0,CF = 1,OF = 1,SF = 1.
- Result =
Pro Tip: Memorize the 8085/8086 instruction set for ALU operations (e.g., ADD, SUB, ANA for AND, ORA for OR). Examiners often ask for microoperation traces or flag settings in such contexts.
In the real world
- eSewa Transaction Validation: Uses XOR operations to validate transaction hashes between sender and server, ensuring data integrity by comparing recomputed hashes (ZF flag checks for match).
- Pathao Route Optimization: Employs bit shifting (e.g., left shift for scaling distances) to quickly adjust coordinates and calculate shortest paths in real-time.
- Nepali Banks (e.g., NMB, Global IME): Use two’s complement arithmetic for loan interest calculations, ensuring accurate floating-point additions/subtractions for monthly payments.
Based on the TU BITM syllabus for Microprocessor And Computer Architecture (IT236), unit 5.
Discussion
Loading…