Search code examples
c#byteoperationthreshold

Byte operations c#


I have an expression which is supposed to calculate the threshold. The original code was:

float threshold = vertHist.min + ((vertHist.max - vertHist.min)/2);

but was then modifies to:

retVal.threshold = (byte)(minValue + ((maxValue - minValue) >> 1));

I can understand the original code and the logic behind it, but can someone kindly walk me through the latter code, which is a revised version of the former?

Thanks.


Solution

  • >> is the bitwise right shift operator. For positive integers (which you're expecting maxValue - minValue to be) it has the effect of dividing by (a power of) 2, and compilers will in fact sometimes replace a division by two with a right shift for you, so you should avoid replacing a division with a shift unless you specifically require shift behaviour.