ASSEMBLY / CHAPTER 02

Sign extension and zero extension

Master

Preserve the intended interpretation when widening a narrow value.

By the end of this chapter

  • Choose MOVSX or MOVZX
  • Distinguish signed values from bit patterns
  • Track writes to 32-bit destinations

The idea

These conceptual traces use x86-64 NASM-style Intel syntax and perform no browser execution or console I/O. A narrow value has no stored language-level type. Widening an unsigned byte requires zeros in the new high bits; widening a signed byte requires copies of its sign bit. MOVZX and MOVSX express those different operations explicitly.

Destination width still matters after extension. Writing EAX clears the high 32 bits of RAX, even when the value written into EAX was sign-extended from a byte. To obtain a full 64-bit signed result directly, use a 64-bit destination. Read a memory byte only when its address is valid, and state whether the byte represents a signed quantity or an unsigned count before choosing the instruction.

Assembly example
; Conceptual register trace; no I/O
mov al, 0xF6
movzx ecx, al
movsx rax, al
Result
RCX = 246; RAX = -10 as a signed 64-bit value.

The same byte becomes 246 under zero extension and -10 under sign extension.

Try it yourself

Widen bytes 0x00, 0x7F, 0x80, and 0xFF both ways and explain which numeric interpretations change.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which instruction widens a signed byte in AL directly to a signed 64-bit value?