Sign extension: 1011 from 4 bits to 8 — two's complement

exam standardcopy the sign bit, do not pad with zeros

Answer

11111011 = -5

Why this example is worth doing

Widening a signed value means replicating the sign bit into the new positions, not padding with zeros. Zero-padding here would turn −5 into +11. The page shows both and the resulting values, because this is the operation behind every widening load instruction and the difference between the signed and unsigned variants of them. It is also where casting bugs in C come from.

Try your own input in the Two’s complement. Encode and decode signed binary at any width, with overflow and sign extension.

How the answer is reached

Extend 1011 from 4 to 8 bits

sign bit1replicated 4 times to the left

Both extensions, side by side — Extend 1011 from 4 to 8 bits
extensionbitsvalue
sign1111 1011-5
zero0000 101111
Warning:

Zero extension changes the value from -5 to 11: it is only correct for unsigned data.

Compare with

Open this example in the Two’s complement

The field arrives filled in with this example’s input.

Note:

Notation this page assumes

  • Bit strings are written most significant bit first, and bit 0 is the least significant bit.
  • A width is stated explicitly wherever it changes the answer; nothing is silently sign-extended or truncated.
  • Negative values are two’s complement, not sign–magnitude, and the most significant bit is the sign bit.

Sources

  • Knuth, The Art of Computer Programming, Vol. 2, §4.1 “Positional Number Systems” (1997)
  • IEEE 754-2019, Standard for Floating-Point Arithmetic