XCHG Instruction


The XCHG instruction (exchange data) exchanges the contents of two operands.

XCHG — Exchange

Usage: XCHG dest, src

Flag O D I S Z A P C
Result                

Exchanges contents of source and destination.

Clocks
Operands 286 386 486 Size Bytes
reg, reg 3 3 3 2
mem, reg 5 5 5 2-4
reg, mem 5 5 3 2-4
accum, reg 3 3 3 1
reg, accum 3 3 3 1


XCHG allows to exchange two operands without needing a third register or variable to hold a temporary value. The rules for operands in the XCHG are the same as those for the MOV instruction.  
The Three Variants

 XCHG  reg, reg 
 XCHG  reg, mem
 XCHG  mem, reg

 Exchanging X and X+2 (?)
 .data
 X   DWORD 12345678h
 .code
 mov   eax, X
 xchg  ax, X
 mov   X+2, ax
 mov   eax, X
 call  WriteHex
 .data
 X   DWORD 12345678h
 .code
 mov   eax, X
 mov   ebx, OFFSET X
 xchg  ax, [ebx+2]
 xchg  [ebx], ax
 mov   eax, X
 call  WriteHex
 .data
 X   DWORD 12345678h
 .code
 mov   eax, X
 mov   ebx, OFFSET X
 xchg  ax, [ebx]
 xchg  [ebx+2], ax
 mov   eax, X
 call  WriteHex
 Output  Output  Output