XCHG exchanges the contents of two places in one instruction, so no spare register is needed. It is the quickest way to swap two values.
What to build
Read two keys and print them in the opposite order, using XCHG.
Requirements
- Keep the first key in BL and the second key in BH.
- Swap the two registers with a single XCHG.
- Print BL and then BH.
Input
Two characters, then Enter.
Output
The same two characters, swapped, on one line.
Constraints
The two characters are letters or digits.
Example
Input:
ab
Output:
ba
Why it works
Before the swap BL holds the first key and BH the second. XCHG BL, BH exchanges them in one step, so printing BL and then BH gives the second key first. Both operands of XCHG must have the same size, and at most one of them may be in memory.
Examples
ab
ba
x9
9x
Hints
Hint 1
Read the first key into BL and the second into BH: after each read, MOV the key out of AL.
Hint 2
XCHG BL, BH swaps the two registers in one instruction.
Hint 3
Print BL first and BH second, each with AH = 2 and DL.
Solution
Show one correct solution (try it yourself first)
; Swap two keys
.MODEL SMALL
.STACK 100H
.CODE
MAIN PROC
MOV AH, 1
INT 21H
MOV BL, AL ; the first key
INT 21H
MOV BH, AL ; the second key
XCHG BL, BH ; swap them
MOV AH, 2
MOV DL, BL
INT 21H
MOV DL, BH
INT 21H
MOV AH, 4CH
INT 21H
MAIN ENDP
END MAIN
▶ Open this solution in the compiler, then press Visualize to watch it run step by step