I have next code:
std::cout << (-10 >> 1) << std::endl;
std::cout << (-9 >> 1) << std::endl;
std::cout << (-8 >> 1) << std::endl;
std::cout << (-7 >> 1) << std::endl;
std::cout << (-6 >> 1) << std::endl;
std::cout << (-5 >> 1) << std::endl;
std::cout << (-4 >> 1) << std::endl;
std::cout << (-3 >> 1) << std::endl;
std::cout << (-2 >> 1) << std::endl;
std::cout << (-1 >> 1) << std::endl;
The result is:
-5
-5
-4
-4
-3
-3
-2
-2
-1
-1
But why?
-1
is 1111 1111
(for 1 byte), -1 >>
1 must be : 1011 1111
and it is not -1
or 0
! (sign-bit is not shifted, I know)
Can someone explain to me how this works?
1 << 0 is 1 shifted to the left by 0 positions, which is just 1.
The binary representation of 12 is: 1100. 12 >> 1 is equivalent to 0110 which is 6 in decimal.
C Programming from scratch- Master C Programming The >> operator is a signed right shift operator and >>> is an unsigned right shift operator. The left operands value is moved right by the number of bits specified by the right operand.
Bitwise Right shift operator >> is used to shift the binary sequence to right side by specified position.
Standard 5.8/3 (Shift operators) :
The value of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 divided by the quantity 2 raised to the power E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.
So to the question "why ?", the standard answer is : why not.
Right-shifting a negative number is implementation-defined.
Implementations which shift in a sign-extended bit to the leftmost bit, work as you reported.
As for why it is done this way, it's because right-shifting can be used to divide by a power of 2 with round-towards-negative-infinity (e.g. like floor()
) rounding behavior:
(-8 >> 2) == -2
(-9 >> 2) == -3
(-10 >> 2) == -3
(-11 >> 2) == -3
(-12 >> 2) == -3
See this SO question.
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