Definition
Sign extension (RISC-V)
Sign extension means that a smaller signed binary value is converted to a larger one while preserving its numerical meaning. The most significant bit is copied into all newly added higher bits.
For a 12-bit immediate, bit 11 is the sign bit:
- If bit 11 is
0, the value is non-negative, and the added upper bits are all0.- If bit 11 is
1, the value is negative in two’s complement form, and the added upper bits are all1.For example, the 12-bit value
0x7ABbecomes0x000007AB, whereas0xEABbecomes0xFFFFFEAB. This is why sign extension preserves both positive and negative immediate values.
Why?
The CPU operates strictly on 32-bit values. A 12-bit immediate cannot be directly added to a 32-bit register; it must be padded to 32 bits first. If we simply padded with zeroes, a negative 12-bit number like -1 (0xFFF) would incorrectly become the positive value +4095 (0x00000FFF). By copying the sign bit, the two’s complement representation is mathematically preserved. This allows the CPU to correctly add both positive and negative constants using the exact same addition logic.