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?
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 向负无穷大舍入。
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.