What exactly happens here?
a << -5
Obviously it doesn't right shift. But the book I'm reading states:
On one machine, this expression actually does a left shift of 27 bits
My question is; why? What causes a left shift of 27 bits? And what exactly happens when shifting with a negative shift count? Thank you.
The left shift and right shift operators should not be used for negative numbers. The result of is undefined behaviour if any of the operands is a negative number. For example results of both 1 >> -1 and 1 << -1 is undefined. If the number is shifted more than the size of integer, the behaviour is undefined.
Negative shift counts are illegal and cause a ValueError to be raised. A left shift by n bits is equivalent to multiplication by pow(2, n). A long integer is returned if the result exceeds the range of plain integers.
For signed numbers, the sign bit is used to fill the vacated bit positions. In other words, if the number is positive, 0 is used, and if the number is negative, 1 is used. The result of a right-shift of a signed negative number is implementation-dependent.
The number to the left of the operator is shifted the number of places specified by the number to the right. Each shift to the left doubles the number, therefore each left shift multiplies the original number by 2. Use the left shift for fast multiplication or to pack a group of numbers together into one larger number.
Negative integers on right-hand side is undefined behavior in the C language.
ISO 9899:2011 6.5.7 Bit-wise shift operators:
The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
As already answered by other members, it produces undefined behavior. What I would like to mention here is that you quote from the book ( "On one machine" ) seems to be partial. It does not generalize the behavior. The book might also have explained that the behavior is undefined as per the standard. BTW, I was just going through "The New C Standard - An Economic and Cultural Commentary" and found this statement :
The Intel Pentium SAL instruction (generated by both gcc and Microsoft C++ to evaluate left-shifts) only uses the bottom five bits of the shift amount
This very well explains why a left shift of -5 could result into a left shift of 27 ( for 2's complement representation of negative numbers )
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