shifting a binary number to the right in assembly with SAR vs. SHR

可紊 提交于 2019-12-02 00:42:09

问题


We know that when we shift a binary number to the right, it is divided by 2. For the number: 1001 0001. Let's assume that is stored in AX register:

  • If we consider it as unsigned number (which is equal to 145 in decimal): SHR AX, 1 will make AX equal to 0100 1000 which is equal to 72 in decimal, and this is right.

  • But if we consider it as signed number (which is equal to -111 in decimal): SAR AX, 1 will make AX equal to 1100 0100 which is equal to -56 in decimal, and this is wrong because it should be equal to -55 in decimal.

Why?


回答1:


The SHR instruction performs an unsigned shift rights, shifting in zeros:

Input:  1001 0001
        |      |\
        +------+ +--> lost
            v
         +------+
         |      |
Output: 0100 1000
        ^
        +-- added by SHR

On the other hand, the SAR instruction performs a signed shift right, interpreting the most significant bit as a sign. It shifts in copies of the sign bit:

Input:  1001 0001
        |      |\
        +------+ +--> lost
        |   v
        |+------+
        v|      |
Output: 1100 1000
        ^
        +-- preserved (copied) by SAR



回答2:


An arithmetic shift right does a divide by 2 that rounds towards minus infinity.




回答3:


We know that when we shift a binary number to the right, it is divided by 2

This is where the confusion starts!
shl shr sal sar are just shifts - nothing more. If some kind of shift resembles a division by 2 it's more or less a bonus. We can not call this behaviour right or wrong.



来源:https://stackoverflow.com/questions/20790864/shifting-a-binary-number-to-the-right-in-assembly-with-sar-vs-shr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!