PIC Math and SX Math Microcontroller Bit Method

This is a clever (but confusing) trick. It only works on the PIC -- generally there are less-confusing ways to do it on other processors.

swap w and f without a temp register

You have a value (A) in W that you want to swap with the value (B) in some file register X,

  ; Swap (W,X):
  ; from Robin Abbott of Forest Electronic Developments
  ; currently, W contains A. X contains B.
  xorwf X,w ; W := A^B; X = B
  xorwf X   ; W = A^B, X := B^(A^B) = A
  xorwf X,w ; W := (A^B)^A = B; X = A
  ; now W contains B. X contains A.

move a value from X to Y without messing up W

This just builds on the above routine:

  ; X contains A. W contains B.
  movwf Y ; Y := B
  movf  X,W ; W = A
  ; Swap (W,Y):
    xorwf Y,w ; W := A^B. Y = B
    xorwf Y   ; W = A^B.  Y := B^(A^B) = A
    xorwf Y,w ; W := (A^B)^A = B; Y = A
  ; X has never been changed -- it still contains B.
  ; now W contains B (just as at the beginning). Y contains A.

Clever, but it is shorter and faster (not to mention less confusing) to use a temporary variable:

  ; X contains A. W contains B.
  movwf temp
  movf  X,W ; W = A
  movwf Y
  movf  temp,W
  ; X has never been changed -- it still contains B.
  ; now W contains B (just as at the beginning). Y contains A.

swap two variables without a temp register

If you have some value (A) in some file register X, and some value (B) in a different file register Y, and you want to swap them, you can do this:

    ; Swap (X,Y)
    ; from kagato-icss-
    ; currently X contains A. Y contains B.
    MOVF  X,W ; W:=A
    XORWF Y,W ; W:=A^B
    XORWF X,F ; X:=((A^B)^A)=B
    XORWF Y,F ; Y:=((A^B)^B)=A
    ; now X contains B. Y contains A.

details

Robin Abbott of Forest Electronic Developments says:

This might be of use to someone. Recently I had a project where a subroutine took a value in W and saved to a software stack:
movwf Temp
movfw sp        ; Stack pointer
movwf FSR    ; Point to it
movfw Temp
movwf INDF

Trouble is it uses a temporary variable which I didn't have (it is in an interrupt). This alternative which makes use of XOR uses no temporary variable at the expense of 1 extra word:

  movwf FSR
  movfw sp
  xorwf FSR
  xorwf FSR,w
  xorwf FSR
  movwf INDF

I think this may be an old technique - I have vague memories of something similar from the pre-history of programming, but only found a use for

(In ____ notation that would be:

	mov	FSR, W
	mov	W, sp
	xor	FSR, W
	xor	W, FSR
	xor	FSR, W
	mov	0, W

)

related: