Question

// Code I'll be working with
int shift_left2_rightn(int x, int n)
{
    x <<= 2;
    x >>= n;
    return x;
}

Question 1. Left shift = SAL and SHL. My book says they have the same effect. Then why are there two shift operations?

For example:

movl    8(%ebp), %eax    //Get x
_______                  //x <<= 2 

My book gives an answer of

sall    $2, %eax

would

shll    $2, %eax 

also been the correct answer?

Question 2:

In layman's terms what is the difference between SHR and SAR? My book says one is a logical shift (fills with zeroes) and other is arithmetic shift (fills with copies of the sign bit).

Fills what with 0's/sign bits?

For example:

How would I know which one to use with the following assembly instructions?

movl   12(%ebp), %ecx   //Get n
______                  //x >>=n

Back of the book has the answer

sarl   %cl, %eax 

Please explain to me what would happen if we used shrl.

Thanks for your help with understanding this!!

Was it helpful?

Solution

sal and shl are synonymous, they have identical opcodes.

As sar does signed division by 2 rounding numbers towards negative infinity (-Inf), and shr does unsigned division by 2, probably engineers at Intel have decided to incorporate also both sal and shl even if they are synonymous.

Here's an example what shr and sar do:

mov al,0b10001000 ; 0b10001000 = 136d = -120d (2's complement)

shr al,1          ; 0b01000100 =  68d =   68d (2's complement)

mov al,0b10001000 ; 0b10001000 = 136d = -120d (2's complement)

sar al,1          ; 0b11000100 = 196d =  -60d (2's complement)

So shr fills with zeroes, and sar fills with the sign bit.

shr is for unsigned divisions or bit shifts in general, and sar for signed divisions.

OTHER TIPS

There really isn't two different operations, just two names for the same instruction.

If you shift right, there is a difference between signed (SAR) and unsigned values (SHR), so one operation sign extends and the other does not.

When shifting left there is no difference, but it still has two names (SAL and SHL) just for the symmetry with the right shifts. They both map to the same machine code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top