I want alwaysPositive to be assigned a positive number with all possible values for lareValue1 and largeValue2 (these are at least 1).
The following statement causes a buffer overflow:
int alwaysPositive = (largeValue1 + largeValue2) / 2;
I know I can prevent it by substracting and adding:
int alwaysPositive = largeValue1 + ((largeValue2 - largeValue1) / 2);
But in other programming languages I can use an unsigned bitshift to do the trick:
int alwaysPositive3 = (largeValue1 + largeValue2) >>> 1;
How can I do this in C#?
The answers below all solve the problem. There are probably lots of ways to do this, but they all (including my solutions) have one thing in common: they all look obfuscated.
In C programming language, a computation of unsigned integer values can never overflow, this means that UINT_MAX + 1 yields zero. More precise, according to the C standard unsigned integer operations do wrap around, the C Standard, 6.2.
There are two ways to get around this: Cast the numbers to a bigger integer type, then do the addition there, and check if the result is in the right range. Do the addition normally, then check the result (e.g. if (a+23<23) overflow).
C says an expression involving integers overflows, if its result after the usual arithmetic conversions is of a signed typed and cannot be represented in the type of the result.
unchecked((largeValue1 + largeValue2) >> 1)
is another option.
See the documentation for the unchecked keyword.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With