Hi all,

Does anyone know a trick to quickly swap two 32-bit values, conditionally? Actually the translation of the following C++ code:

int x = ...;
int y = ...;

if(x < y)
{
    int t = x;
    x = y;
    y = t;
}

Of course it can be done with a jump or conditional move, but maybe there's an instruction I don't know about that can do it even faster.

Cheers,

c0d1f1ed
Posted on 2005-09-06 09:55:39 by C0D1F1ED
cmpxchg
Posted on 2005-09-06 10:39:51 by comrade
Another solution taken from Hacker's Delight :


cmp x, y
sbb eax, eax  ; x < y ? -1 : 0
xor x, y      ; x ^ y
and eax, x    ; x < y ?  x ^ y : 0
xor y, eax    ; x < y ?  x    : y
xor x, y      ; x < y ?  y    : x
Posted on 2005-09-06 11:24:54 by Dr. Manhattan
Here's another way:


mov edx, y 
sub edx, x 
sbb ecx, ecx 
and ecx, edx 

add x, ecx      ; x = min(x,y) 
sub y, ecx      ; y = max(x,y)


Spara
Posted on 2005-09-06 13:03:18 by Sparafusile