The XCHG instruction
Exchange the contents of a register or a memory location with the contents of a register.
The XCHG instruction format
| Instruction | Description |
|---|---|
| XCHG AX, reg16 | Exchange the contents of reg16 with AX. |
| XCHG reg16, AX | Exchange the contents of AX with reg16. |
| XCHG reg/mem8, reg8 | Exchange the contents of reg8 with reg/mem8. |
| XCHG reg8, reg/mem8 | Exchange the contents of reg/mem8 with reg8. |
| XCHG reg/mem16, reg16 | Exchange the contents of reg16 with reg/mem16. |
| XCHG reg16, reg/mem16 | Exchange the contents of reg/mem16 with reg16. |
Exchanges the contents of the destination (first) and source (second) operands. The operands can be two general-purpose registers, or a register and a memory location. When a memory operand is referenced, the locking protocol of the processor is automatically implemented for the duration of the exchange operation, regardless of the presence or absence of the lock prefix or the IOPL value.
This instruction is useful for implementing semaphores or similar data structures for process synchronization.
Usage example
title .model small .stack 100h code segment public ; Start of the code segment assume cs:code main proc ; Start of the main procedure mov al, 11h ; Copy the value 17h into the al register mov bl, 22h ; Copy the value 34h into the bl register xchg al, bl ; Exchange the contents of al and bl mov ax, 4C00h ; Copy the process termination function number into ah and the value into al int 21h ; Call the interrupt main endp ; End of the main procedure code ends ; End of the code segment end main ; End of file. The main procedure is the entry point
Example taken from the textbook "HANDYFAR - MASM (Evgeny Sergeevich Dovgopolov)".
Processor status flags
CF
NoPF
NoAF
NoZF
NoSF
NoTF
NoIF
NoDF
NoOF
No