Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

.net - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...