Skip to content
BetterDL

Register swap

Also called: swapping registers, register exchange, exchange registers

Exchanging the contents of two registers. With simultaneous transfers it takes one clock edge: R1 ← R2, R2 ← R1. One transfer per edge needs a temporary.

A register swap exchanges the contents of two registers.

In hardware this can happen in one clock edge:

R1 ← R2, R2 ← R1

The comma in register transfer notation means both transfers happen at the same edge. Both registers sample their inputs at the same instant, using the values from before the edge, and only then do they update. So R1 receives R2's old value and R2 receives R1's old value. No temporary register is needed.

This is the same edge rule that makes a shift register work: every flip-flop reads its neighbor's old value.

Done as two separate edges, it fails: R1 ← R2 first overwrites R1, so R2 ← R1 then copies R2's own value back. Both end up equal.

If a datapath can only do one transfer per edge, it needs a third register and three edges:

  1. R3 ← R1
  2. R1 ← R2
  3. R2 ← R3

Software has the same problem, which is why a swap in most programming languages needs a temporary variable.

Worked examples

Example

One-edge swap

R1 = 1100 and R2 = 0101. At one edge: R1 ← R2, R2 ← R1.

  1. 1.

    Before the edge, R1's input is R2 = 0101, and R2's input is R1 = 1100.

  2. 2.

    At the edge both load together.

  3. 3.

    After: R1 = 0101, R2 = 1100. Swapped.

Example

The two-edge mistake

Same starting values, but done as R1 ← R2 at edge 1 and R2 ← R1 at edge 2.

  1. 1.

    Edge 1: R1 = 0101. R2 is still 0101.

  2. 2.

    Edge 2: R2 ← R1 = 0101.

  3. 3.

    Both registers hold 0101. R1's original 1100 is lost.

Common mistakes

  • Thinking hardware needs a temporary register for a swap. With both transfers at one edge, it does not.

  • Splitting the swap over two edges without a temporary.

Practice Register swap

Interactive questions with instant feedback and a worked solution for every wrong answer.

Learn it step by step

Register swap is taught in Registers.