问题
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
145in decimal):SHR AX, 1will makeAXequal to0100 1000which is equal to72in decimal, and this is right.But if we consider it as signed number (which is equal to
-111in decimal):SAR AX, 1will makeAXequal to1100 0100which is equal to-56in decimal, and this is wrong because it should be equal to-55in 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