Course contentsShow
← Embedded Systems & Computer Architecture
Lesson 108 of 9362. Instruction Set Architecture and CPU MicroarchitectureFree lesson

Implementing Immediate Value Constraints and Sign Extension

Apply sign extension techniques to correctly process immediate values within instructions when dealing with varying bit-width operand requirements.

In this lesson, you will learn how computers bridge the gap between small, fixed-size instruction fields and the larger registers they need to update.

The Problem of "Short" Constants

In many RISC architectures, an instruction is a fixed width (like 32 bits). If you want to add a constant value to a register using an ADDI (Add Immediate) instruction, that constant cannot occupy all 32 bits, because the instruction must also hold the operation code (opcode) and the register identifiers.

Often, you might only have 12 bits available for your immediate value. But what happens if you want to represent a negative number, like -5, using only those 12 bits? You cannot simply pad the remaining leading bits with zeros, or you would turn a negative value into a massive positive one.

The Solution: Sign Extension

Sign extension is the hardware mechanism that stretches a shorter value into a longer one while preserving its mathematical sign.

When the CPU identifies that an instruction uses a signed immediate value, it looks at the Most Significant Bit (MSB) of that immediate field—the "sign bit."

  1. If the sign bit is 0 (positive), the hardware fills the new, higher-order bits with 0s.
  2. If the sign bit is 1 (negative), the hardware fills the new, higher-order bits with 1s.

Consider an 8-bit example being extended to 16 bits:

  • Positive 5: 0000 0101 becomes 0000 0000 0000 0101 (Sign bit 0 copied)
  • Negative 5 (in 2's complement): 1111 1011 becomes 1111 1111 1111 1011 (Sign bit 1 copied)

By replicating the sign bit, the CPU ensures that the value remains identical in magnitude and sign when it is moved into a 32-bit or 64-bit register for arithmetic processing. Without this logic, your CPU would be unable to perform basic subtraction or address offsets using negative constants.

Key Takeaway: Sign extension preserves the mathematical integrity of immediate values by copying the sign bit into all new, high-order positions during bit-width expansion.