什么是">>"运营商在C#中吗?运营商、QUOT、GT

2023-09-02 21:47:05 作者:敲击岁月

我就遇到了这个说法在一块code:

I ran into this statement in a piece of code:

Int32 medianIndex = colorList.Count >> 1;

colorList 是类的列表的System.Drawing.Color

现在的说法应该是检索列表的平均指数..像半个点的..但我不明白怎么>> 符号的工作原理,以及如何将1应该给平均指数..我想AP preciate一些帮助:•

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

推荐答案

>> 符执行的位移位。

这位前pression >> 1 几乎*同 / 2 ,以便程序员在计算指数 colorList.Count / 2 这是**的平均。要明白这是为什么,你需要看一下所涉及的数字的二进制再presentation的情况。例如,如果你在你的列表中25种元素:

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

在一般使用位运算符时,真的要执行一个部门是一个不好的做法。这可能是一个premature优化作出,因为程序员认为这将是更快地执行,而不是一个部门的按位运算。这将是更加明确写一个部门,我不会感到惊讶,如果这两种方法的性能相媲美。

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.

*这位前pression X>> 1 给出了相同的结果 X / 2 对于所有正整数,所有负偶数。但是它给出了不同的结果为负数的奇数。例如 -101>> 1 == -51 ,而 -101 / 2 == -50

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