8

I am learning assembly language (specific to x86). I have understood that the SAL and SHL works in similar way (clearing the lsb and carrying the msb to CF) from here Difference between SHL and SAL in 80x86.

Considering that SHR and SAR doesn't operate in similar way (the latter keeping the msb unchanged).

I would like to have a clear concept about why the functionality of Shift Arithmetic Right SAR is defined different from Shift Right SHR but at the same time the SHL and SAL are kept with similar functionality ?

Community
  • 1
  • 1
Abrar
  • 6,874
  • 9
  • 28
  • 41
  • 8
    Shifting right is different for signed and unsigned values. Shifting left is not. I believe `SHL` and `SAL` is actually a single instruction with two names. – Bo Persson Mar 12 '16 at 11:14
  • 6
    _"I believe SHL and SAL is actually a single instruction with two names."_ Correct. Just like `JE` and `JZ`. – Michael Mar 12 '16 at 11:15
  • @user3528438: That doesn't really explain it, unless you mean to implement C in a similar way to other platforms. The C standard specifically leaves right shift of signed values implementation-defined behaviour. It might or might not sign-extend, and using `shr` would be a perfectly valid C implementation. Since `sar` exists, it makes more sense to use it. It's possible to make a standards-conforming C implementation that is extremely unfriendly to use and violates many assumptions made in a lot of code. – Peter Cordes Mar 12 '16 at 16:16
  • 2
    @PeterCordes So that's the difference between a good architect and an ass. – user3528438 Mar 12 '16 at 21:13

1 Answers1

10

Because there's nothing to preserve in case of a left shift. In those cases that a left shift changes the sign (which you might have wanted to prevent somehow), the result without overflow would not fit in a register (this is automatically so - if it did fit, then it wouldn't have overflowed to begin with). So there's nothing you can do about it anyway.

But right shift can't overflow, it makes the number smaller (or it stays the same). So now you can choose, do I keep the top bit intact or not.

harold
  • 61,398
  • 6
  • 86
  • 164