XCHG Instruction


The 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


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

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

Exchanging X and X+2 (?)
xchg ax, X xchg ax, [ebx+2] xchg ax,[ebx]
 INCLUDE Irvine32.inc
 .data
  X   DWORD 12345678h
 .code
 main PROC
  mov   eax, X
  xchg  ax, X
  mov   X+2, ax
  mov   eax, X
  call  WriteHex
  exit
 main ENDP
 END main
	
 INCLUDE Irvine32.inc
 .data
  X   DWORD 12345678h
 .code
 main PROC
  mov   eax, X
  mov   ebx, OFFSET X
  xchg  ax, [ebx+2]
  xchg  [ebx], ax
  mov   eax, X
  call  WriteHex
  exit
 main ENDP
 END main
      
 INCLUDE Irvine32.inc
 .data
  X   DWORD 12345678h
 .code
 main PROC
  mov   eax, X
  mov   ebx, OFFSET X
  xchg  ax, [ebx]
  xchg  [ebx+2], ax
  mov   eax, X
  call  WriteHex
  exit
 main ENDP
 END main
Output Output Output

 

 

 

 

 

 






      I’ll call you later. Don’t call me later.    
      Call me Dad!