Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>x / 2</code> is clearer, and <code>x &gt;&gt; 1</code> is not much faster (according to a micro-benchmark, about 30% faster for a Java JVM). As others have noted, for negative numbers the rounding is slightly different, so you have to consider this when you want to process negative numbers. Some compilers may automatically convert <code>x / 2</code> to <code>x &gt;&gt; 1</code> if they know the number can not be negative (even thought I could not verify this). </p> <p>Even <code>x / 2</code> may not use the (slow) division CPU instruction, because <a href="http://gcc.godbolt.org/#%7B%22version%22%3A3%2C%22filterAsm%22%3A%7B%22labels%22%3Atrue%2C%22directives%22%3Atrue%2C%22commentOnly%22%3Atrue%7D%2C%22compilers%22%3A%5B%7B%22sourcez%22%3A%22JYOwLgBAZg9jAUFSWBAlAKAN4YhATgKZgCu%2BISEA9BAEwDcGAvkAAA%3D%3D%22%2C%22compiler%22%3A%22g520%22%2C%22options%22%3A%22-O1%20-std%3Dc%2B%2B0x%20-fomit-frame-pointer%22%7D%5D%7D" rel="nofollow noreferrer">some shortcuts are possible</a>, but it is still slower than <code>x &gt;&gt; 1</code>.</p> <p>(This is a C / C++ question, other programming languages have more operators. For Java there is also the unsigned right shift, <code>x &gt;&gt;&gt; 1</code>, which is again different. It allows to correctly calculate the mean (average) value of two values, so that <code>(a + b) &gt;&gt;&gt; 1</code> will return the mean value even for very large values of <code>a</code> and <code>b</code>. This is required for example for binary search if the array indices can get very large. There was <a href="http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html" rel="nofollow noreferrer">a bug in many versions of binary search</a>, because they used <code>(a + b) / 2</code> to calculate the average. This doesn't work correctly. The correct solution is to use <code>(a + b) &gt;&gt;&gt; 1</code> instead.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload