Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why -1 >> 1 is -1 ? And 1 >> 1 is 0!

Tags:

c++

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?

like image 312
Max Avatar asked Nov 29 '10 21:11

Max


People also ask

What does 1 << 0 do in C?

1 << 0 is 1 shifted to the left by 0 positions, which is just 1.

What does >> 1 do in Java?

The binary representation of 12 is: 1100. 12 >> 1 is equivalent to 0110 which is 6 in decimal.

What does >> mean in code?

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.

What does >> indicate in C?

Bitwise Right shift operator >> is used to shift the binary sequence to right side by specified position.


2 Answers

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.

like image 176
icecrime Avatar answered Oct 25 '22 01:10

icecrime


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.

like image 33
Jason S Avatar answered Oct 25 '22 03:10

Jason S