Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is >>> operation in C++

Tags:

c++

syntax

In this blog post the author has suggested the following as the bug fix:

 int mid = (low + high) >>> 1;

Does anyone know what is this >>> operator? Certainly its not there on the following operator reference list:

  • http://msdn.microsoft.com/en-us/library/x04xhy0h%28v=vs.71%29.aspx
  • http://www.cplusplus.com/doc/tutorial/operators/

What is it and how does that solve the overflow problem?

like image 826
Muhammad Hasan Khan Avatar asked Apr 03 '11 12:04

Muhammad Hasan Khan


People also ask

What does >> operator mean in C?

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

What do you mean by >>> operators in Java?

An operator, in Java, is a special symbols performing specific operations on one, two or three operands and then returning a result. The operators are classified and listed according to precedence order. Java operators are generally used to manipulate primitive data types.


1 Answers

>>> is the logical right shift operator in Java.

It shifts in a zero on the left rather than preserving the sign bit. The author of the blog post even provides a C++ implementation:

mid = ((unsigned int)low + (unsigned int)high)) >> 1;

... if you right-shift unsigned numbers, preserving the sign bit doesn't make any sense (since there is no sign bit) so the compiler obviously uses logical shifts rather than arithmetic ones.

The above code exploits the MSB (32rd bit assuming 32 bit integers): adding low and high which are both nonnegative integers and fit thus into 31 bits never overflows the full 32 bits, but it extends to the MSB. By shifting it to the right, the 32 bit number is effectively divided by two and the 32rd bit is cleared again, so the result is positive.

The truth is that the >>> operator in Java is just a workaround for the fact that the language does not provide unsigned data types.

like image 156
Alexander Gessler Avatar answered Sep 26 '22 00:09

Alexander Gessler