Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I prevent a integer overflow in C# using an unsigned right shift?

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.

like image 524
Paco Avatar asked Sep 22 '08 20:09

Paco


People also ask

How does C handle integer overflow?

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.

How do you fix arithmetic overflow in C?

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

What happens if there is overflow in C?

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.


1 Answers

unchecked((largeValue1 + largeValue2) >> 1) is another option.

See the documentation for the unchecked keyword.

like image 161
Doug McClean Avatar answered Oct 08 '22 01:10

Doug McClean