Skip to content

Instructions

x86-64

Sign extension (CBW / CWDE / CDQE / CWD / CDQ / CQO)

The accumulator-widening instructions that replicate the sign bit before signed division — and the family that explains MOVSX-style behaviour.

These tiny, operand-less instructions all do the same thing: they replicate the top (sign) bit of the accumulator across a wider register, preserving the signed value. They come in two families.

Widen the accumulator in place

CBW / CWDE / CDQE double the width within the accumulator:

InstrEffect
CBWsign-extend ALAX
CWDEsign-extend AXEAX
CDQEsign-extend EAXRAX (Intel syntax also accepts the cdqe mnemonic)

Widen the accumulator into DX/EDX/RDX

CWD / CDQ / CQO sign-extend the accumulator into the next register up, forming the double-width dividend that IDIV needs:

InstrEffect
CWDsign-extend AXDX:AX
CDQsign-extend EAXEDX:EAX
CQOsign-extend RAXRDX:RAX
asm
mov eax, 50
mov ecx, -3
cdq               ; EDX = 0xFFFFFFFF (sign of EAX), forming EDX:EAX
idiv ecx          ; EAX = -16, EDX = 2

Without the cdq, EDX would hold stale bits and the signed divide would produce garbage — or fault. This is the reason cdq/cqo exist and why they almost always sit immediately before idiv.

Reverse-engineering notes

  • cdq/cqo before idiv → signed division. The unsigned counterpart zeroes the high half with xor edx, edx before div. This pairing is the fastest way to tell signed from unsigned division in a disassembly.
  • cdqe (often shown as cltq in AT&T/GCC output) appears when a 32-bit int index is sign-extended to a 64-bit pointer offset — a hallmark of array indexing with signed int subscripts.
  • MOVSX/MOVSXD (MOVZX / MOVSX) generalise the same idea to arbitrary register pairs; the Cxx instructions are just the compact, accumulator-only special cases.
  • Forgetting these is a classic hand-written-assembly bug: an idiv with an uninitialised edx gives wrong results for negative dividends.

See also: DIV / IDIV · MOVZX / MOVSX · Two's complement.

Try it — Virtual CPU

open full playground →
  1. 1 mov eax, 50
  2. 2 mov ecx, -3
  3. 3 cdq
  4. 4 idiv ecx
  5. 5
step 0
Loading emulator…