A Little Assembler Magic

In most languages, if you need to swap the contents of two variables, say X and Y, it normally requires a third temporary location:

 Temp = X;

 X = Y;

Y = Temp;

But in assembly language, if the two variables are stored in registers (or even in memory), you can swap them without using a third register (or variable).  Here’s the code that uses an exclusive or to swap the values:

XR    R5,R3

XR    R3,R5

XR    R5,R3

Try it yourself with some real values and you can almost see the bits exchanging places.  Presto, Changeo!  A little assembler magic. 

Leave a comment

Filed under IBM Mainframe Assembler

Leave a Reply