Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the ">>" operator in C# do?

I ran into this statement in a piece of code:

Int32 medianIndex = colorList.Count >> 1;

colorList is a list of class System.Drawing.Color.

Now the statement is supposed to retrieve the median index of the list .. like the half point of it .. but I can't understand how that >> symbol works and how the "1" is supposed to give the median index .. I would appreciate some help :S

like image 923
Majd Avatar asked Aug 14 '10 23:08

Majd


1 Answers

The >> operator performs a bit shift.

The expression >> 1 is almost* the same as / 2 so the programmer was calculating the index colorList.Count / 2 which is** the median. To understand why this is the case you need to look at the binary representation of the numbers involved. For example if you have 25 elements in your list:

n     : 0 0 0 1 1 0 0 1 = 25
         \ \ \ \ \ \ \
n >> 1: 0 0 0 0 1 1 0 0 = 12

In general using a bitwise operator when really you want to perform a division is a bad practice. It is probably a premature optimization made because the programmer thought it would be faster to perform a bitwise operation instead of a division. It would be much clearer to write a division and I wouldn't be surprised if the performance of the two approaches is comparable.

*The expression x >> 1 gives the same result as x / 2 for all positive integers and all negative even integers. However it gives a different result for negative odd integers. For example -101 >> 1 == -51 whereas -101 / 2 == -50.

**Actually the median is only defined this way if the list has an odd number of elements. For an even number of elements this method will strictly speaking not give the median.

like image 148
Mark Byers Avatar answered Oct 07 '22 23:10

Mark Byers