IT236 Microprocessor And Computer Architecture

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.

Instruction FetchDecodeExecute (ALU)Memory AccessWriteback
Simplified 5-stage pipeline: ALU operates in the Execute stage.
Registers[object Object]ALU[object Object]Flags Register[object Object]Control Unit[object Object]
ALU as the core processing unit: operands from registers/memory → ALU → result + flags → control unit for branching.

ALU Operations

The ALU performs two broad categories of operations:

  1. Arithmetic Operations:
    • Addition (ADD), Subtraction (SUB), Increment (INC), Decrement (DEC), Multiplication (MUL), Division (DIV).
    • Example: ADD B, C adds the contents of register B and C, storing the result in B.
  2. Logic Operations:
    • AND, OR, XOR, NOT, Compare (CMP), Test (TEST).

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.

08162431Zero Flag (ZF)1 bitsCarryFlag (CF)1 bitsOverflow Flag (O1 bitsSign Flag (SF)1 bitsParityFlag (PF)1 bitsAuxiliary Flag (1 bitsDirection Flag (1 bitsInterrupt Flag (1 bits
Typical 8-bit Flags Register (x86-like) after ALU operations. Only ZF, CF, OF, SF are essential for branching.

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).

0011121314151617Sign Bit (1 = negative)LSB
Two’s complement of +7 (`0111`) is `1001` (-7). Invert bits +1 → `1000` +1 = `1001`.
08162431Sign Bit1 bitsExponent8 bitsMantissa23 bits
IEEE 754 Single-Precision Floating-Point Format (Example: 100,000 stored as 0x42C80000)

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.
  • 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).

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 as 0x42C80000 in IEEE 754 single-precision).
  • Interest rate = 0.05 (stored as 0x3E666666).
  • The ALU computes:
    Interest = Principal × Rate = 100,000 × 0.05 = 5,000
    
    The microprocessor performs:
    1. Floating-point multiplication (ALU handles exponent/mantissa separately).
    2. Rounds the result to the nearest representable value.
    3. 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 remainder 0000 (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).

[object Object][object Object][object Object]ABCALU
ALU implements logic gates as combinational circuits. Example: AND gate = `output = A AND B`.

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:

  1. The sender’s phone computes Hash = XOR(Amount, SecretKey).
  2. 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).

Shift and Rotate Operations

These operations move bits within a register or memory location, often used for multiplication/division or data alignment.

10011213MSB (Sign Bit, preserved)New bit filled from signLSB (discarded)
Arithmetic Shift Right (ASR) on `1011` (signed -3 → -1). Sign bit replicates to maintain magnitude.

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:

  1. A 16-bit integer represents distance in meters (e.g., 0x03E8 = 1000 meters).
  2. 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 DIV instruction, saving cycles.

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

  1. Align Exponents: Shift the mantissa of the smaller exponent to match the larger.
  2. Add Mantissas: Perform binary addition on the aligned mantissas.
  3. Normalize: Adjust the result to standard form (1.xxxx × 2^exponent).
  4. Round: Truncate or round to fit the mantissa size.
  5. Check Flags: Set flags for overflow/underflow.

Mermaid Diagram: Floating-Point Addition Pipeline

Worked Example: YouTube Video Buffering YouTube uses floating-point arithmetic to:

  1. Calculate buffering time based on bitrate and network speed.
    • Example: Buffer = VideoSize / NetworkSpeed.
    • If VideoSize = 10,000,000 bytes and NetworkSpeed = 2,000,000 bytes/sec, the ALU computes:
      BufferTime = 10,000,000 / 2,000,000 = 5.0 seconds
      
  2. The result is stored as a floating-point value (0x40A00000 in IEEE 754).

## In the Real World

  1. eSewa (Transaction Validation)

    • Idea Used: XOR operations and flags (ZF).
    • How: eSewa computes a checksum using XOR on transaction details (amount, timestamp, secret key). The server verifies the checksum by recomputing the XOR and comparing it to the received value. If ZF is set (checksums match), the transaction proceeds; otherwise, it’s flagged as fraudulent.
  2. 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.
  3. 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,000 at 8% annual interest:
      • Monthly interest = 5,000,000 × (8/12)/100 = 33,333.33.
      • The ALU handles the multiplication and rounding, while OF ensures no overflow occurs during large-scale calculations.
  4. 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.5 belongs to the subnet 192.168.1.0/24:
      AND AX, 0xFFFFFF00   ; Mask the last 8 bits
      CMP AX, 0xC0A80100  ; Compare with subnet
      
      • The AND operation isolates the network portion, and CMP sets flags for routing decisions.

## Exam Tip

This unit is heavily tested on:

  1. 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.
  2. 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.
  3. 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 ASR for distance conversion and AND for IP subnet matching.
  4. Assembly-Level Operations:

    • Know microoperations for stack operations (e.g., POP in 8085):
      • POP B: SP ← SP + 1; B ← M[SP] (where M is memory).
    • Example question: "Write down microoperations for POP operation in register stack." → Answer: Increment stack pointer, load register from memory.
  5. Flag Analysis:

    • For any arithmetic/logic operation, predict all affected flags.
    • Example: SUB B, C where B = 0x05, C = 0x07:
      • Result = 0xFF (overflow), ZF = 0, CF = 1, OF = 1, SF = 1.

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…