Transferred from:Http://dev.csdn.net/article/29/29329.shtm
For more information about logical shift and arithmetic shift, see the quick Bi questions section. .
Previously, we saw that in C ++ standards, the behavior of the shift operator (<,>) out of the bounds is not determined:
The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand.
I did not go into this issue at the time. A netizen wrote a letter a few days ago asking about this, and I found that this is related to the Intel CPU shift operation. The following is a letter from the netizen and my reply:
Hello! Operator <as an efficient operation in bitwise operations, But I encountered a problem: the following is a problem that is hard to understand in the VC environment, which is marked below.
# Include <stdio. h>
Void main ()
{
Unsigned int I, J;
I = 35;
// Why are the results of the two left-shift operations different?
J = 1 <I; // J is 8
J = 1 <35; // J is 0
}
I don't know where it is.
The reason is as follows: I = 35; j = 1 <I; the two statements are compiled into the following machine commands without VC optimization:
MoV dword ptr [I], 23 h
MoV eax, 1
MoV ECx, dword ptr [I]
SHL eax, Cl
MoV dword ptr [J], eax
In the SHL statement, eax = 1, CL = 35. When Intel CPU executes the SHL command, it first performs and operations on CL and 31 to limit the number of shifts left to 31 or less. Because 35 & 31 = 3, this command is equivalent to moving 1 to three places, and the result is 8.
J = 1 <35; a constant operation. Even if VC is not optimized, the compiler directly calculates the result of 1 <35. When the VC compiler finds that 35 is greater than 31, the result is directly set to 0. The machine commands generated by this line of code compilation are:
MoV dword ptr [J], 0
In the above two cases, if the optimization switch of the VC compiler is enabled (for example, compiled into the release version), the compiler will directly set the result to 0.
Therefore, in C/C ++, the shift operation should not exceed the limit. Otherwise, the result is unpredictable.
The following describes how the SHL command limits the number of shifts in Intel documents:
The destination operand can be a register or a memory location. the Count operand can be an immediate value or register Cl. the count is masked to 5 bits, which limits the Count range to 0 to 31. A special opcode encoding is provided for a count of 1.