Sign Extension When Widening a Field

Sign extension copies the original sign bit into the new high positions to preserve a two's-complement value.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Compare two widening choices
  2. Choose by the interpretation
  3. Replicate the source sign through every new high position
  4. Verify the general place-value difference

Compare two widening choices

Four-bit 1101 means minus three. Sign extension to eight bits gives 11111101 and preserves that value. Zero extension gives 00001101, or thirteen. See reading two's complement.

Choose by the interpretation

For an unsigned source field, zero extension is usually appropriate. A signed source needs sign extension before arithmetic with the wider value. Test a negative case and a positive case under the function contract.[1]

Replicate the source sign through every new high position

A five-bit two's-complement word 10110 means minus ten. Widening to eight bits yields 11110110. Filling the new positions with zeros gives twenty-two and changes the value. Nonnegative patterns continue with zeros under the signed rule as well. See reading two's complement.

Source 10110: 22 unsigned, -10 signed
Sign-extended 11110110: 246 unsigned, -10 signed
Zero-extended 00010110: 22 in either interpretation

Verify the general place-value difference

Copying a set sign to new positions adds \(2^W-2^w\) to the unsigned representation when widening from \(w\) to \(W\). Subtracting \(2^W\) for signed interpretation leaves the original unsigned value minus \(2^w\). Test the smallest negative and largest positive source values.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩