Integer absolute value in MIPS?

aherlambang picture aherlambang · Feb 22, 2010 · Viewed 36.4k times · Source

Do you have any simple ways to make a value in a register in MIPS as an absolute value?

Answer

Michael picture Michael · Apr 17, 2013

Here's a branch-less variant:

# input and output in $t0
sra $t1,$t0,31   
xor $t0,$t0,$t1   
sub $t0,$t0,$t1    

How does this work?
First, $t1 is filled with the sign-bit of $t0. So if $t0 is positive $t1 will be set to 0, and if $t0 is negative $t1 will be set to 0xFFFFFFFF.

Next, each bit of $t0 is inverted if $t1 is 0xFFFFFFFF, or left unchanged if $t1 is 0. It just so happens that inverting all bits of a number is the same as setting it to (-number)-1 (in two's complement).

Finally, either 0xFFFFFFFF (which equals -1) or 0 is subtracted from the intermediate result.

So if $t0 originally was negative you'll get:
$t0 = ($t0 ^ 0xFFFFFFFF) - 0xFFFFFFFF == (-$t0 - 1) - -1 == (-$t0 - 1) + 1 == -$t0.
And if it originally was positive you'll get:
$t0 = ($t0 ^ 0) - 0 == $t0.