sra(shift right arithmetic) vs srl (shift right logical)

user591931 picture user591931 · Jun 7, 2011 · Viewed 34.5k times · Source

Please take a look at these two pieces of pseudo-assembly code:

1)

li $t0,53

sll $t1,$t0,2
srl $t2,$t0,2
sra $t3,$t0,2

print $t1  
print $t2  
print $t3  

2)

li $t0,-53


sll $t1,$t0,2
srl $t2,$t0,2
sra $t3,$t0,2

print $t1
print $t2
print $t3

in the first case the output is:
212
13
13

in the latter is:
-212
107374...
-14
But shouldn't : sra (-53) = - (srl 53) ?

Answer

ikegami picture ikegami · Jun 7, 2011
-53 = 1111111111001011

           sra 2

      1111111111110010(11) = -14
       ^^              ^^
      sign           dropped
    extension

Because the extra bits are simply dropped for both positive and negative results, the result is always rounded down if you view the shift as a division.

 53 sra 2 = floor( 53 / 2^2) = floor( 13.25) =  13
-53 sra 2 = floor(-53 / 2^2) = floor(-13.25) = -14