SWAPF Data Movement

Exchange the upper and lower nibbles of a register.

SyntaxSWAPF f, d
Operandsf: register address 0-127 (bank bits come from STATUS); d: 0 or w puts the result in W, 1 or f puts it back in f
Operation(f<3:0>) → destination<7:4>, (f<7:4>) → destination<3:0>
Status bitsNone
Words / cycles1 word, 1 cycle
Encoding00 1110 dfff ffff

How it works

SWAPF exchanges the two 4-bit halves of register f and puts the result in W or back in f.

Because it changes no STATUS bits, SWAPF is the instruction interrupt routines use to save and restore STATUS: MOVF would change Z on the way back.

Example

; SWAPF example from picsimulator.com/instructions/swapf.html
    list p=16f84a
    include <p16f84a.inc>

    org 0
    movlw 0xA5
    movwf 0x20
    swapf 0x20, w     ; W = 0x5A, 0x20 still holds 0xA5

W becomes 0x5A and the register is unchanged because the destination is W.

Open this example in the simulator

Watch out for

  • In an interrupt routine, save STATUS with SWAPF STATUS, W and restore it with SWAPF (twice) so the flags the main program was using come back intact.

Related instructions