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.
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.
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.
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.
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 INDFTrouble 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 INDFI 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:
file: /Techref/microchip/math/bit/swap.htm, 4KB, , updated: 2004/8/19 17:51, local time: 2024/11/22 00:51,
3.142.131.51:LOG IN
|
©2024 These pages are served without commercial sponsorship. (No popup ads, etc...).Bandwidth abuse increases hosting cost forcing sponsorship or shutdown. This server aggressively defends against automated copying for any reason including offline viewing, duplication, etc... Please respect this requirement and DO NOT RIP THIS SITE. Questions? <A HREF="http://ecomorder.com/techref/microchip/math/bit/swap.htm"> swap w and f without a temp register</A> |
Did you find what you needed? |
Welcome to ecomorder.com! |
Welcome to ecomorder.com! |
.