Instructions
x86-64Sign 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:
| Instr | Effect |
|---|---|
CBW | sign-extend AL → AX |
CWDE | sign-extend AX → EAX |
CDQE | sign-extend EAX → RAX (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:
| Instr | Effect |
|---|---|
CWD | sign-extend AX → DX:AX |
CDQ | sign-extend EAX → EDX:EAX |
CQO | sign-extend RAX → RDX:RAX |
mov eax, 50
mov ecx, -3
cdq ; EDX = 0xFFFFFFFF (sign of EAX), forming EDX:EAX
idiv ecx ; EAX = -16, EDX = 2Without 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/cqobeforeidiv→ signed division. The unsigned counterpart zeroes the high half withxor edx, edxbeforediv. This pairing is the fastest way to tell signed from unsigned division in a disassembly.cdqe(often shown ascltqin AT&T/GCC output) appears when a 32-bitintindex is sign-extended to a 64-bit pointer offset — a hallmark of array indexing with signedintsubscripts.MOVSX/MOVSXD(MOVZX / MOVSX) generalise the same idea to arbitrary register pairs; theCxxinstructions are just the compact, accumulator-only special cases.- Forgetting these is a classic hand-written-assembly bug: an
idivwith an uninitialisededxgives wrong results for negative dividends.
See also: DIV / IDIV · MOVZX / MOVSX · Two's complement.
Try it — Virtual CPU
open full playground →- 1 mov eax, 50
- 2 mov ecx, -3
- 3 cdq
- 4 idiv ecx
- 5