On Visual Studio compiling following C code , the result is 4 .
void main() { int c = 1; c = c<<34;}
The assembly code as seen from on Visual Studio disassembly window is
shl eax,22h
From assembly , its easy to see that we are shifting 34. Since the integer here is 4 bytes , from the results it is obvious that modulo operation was carried out on machine level to make this work as shift by 2.
I was wondering if this behavior is standardized across platforms or varies across platforms?
Logical bit shifting may be useful for multiplying or dividing unsigned integers by powers of two. For example, if the value "0001" or "1" is shifted left, it becomes "0010" or "2," shifted to the left again it becomes "0100," or "4." Shifting to the right has an opposite effect of dividing the value by two per shift.
Left Shifts When shifting left, the most-significant bit is lost, and a 0 bit is inserted on the other end. The left shift operator is usually written as "<<".
The bitwise shift operators move the bit values of a binary object. The left operand specifies the value to be shifted. The right operand specifies the number of positions that the bits in the value are to be shifted. The result is not an lvalue.
Bit-shifting is still faster, but for non-power-of-two mul/div by the time you do all your shifts and add the results it's slower again.
Undefined behavior happens. That's standardized by the language standard (See section 6.5.7 Bitwise shift operators
of the C standard from 1999). The observable effects of UB are not standardized, however, and may vary.
As for shl eax, 22h
, the shift count is going to be truncated to 5 bits by the CPU (see the documentation) and this instruction will really behave as shl eax, 2
.
According to this article on MSDN:
The result is undefined if the right operand of a shift expression is negative or if the right operand is greater than or equal to the number of bits in the (promoted) left operand. No shift operation is performed if the right operand is zero (0).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With