c# - Check for arithmetic overflow and get overflow count? -


what appropriate way detect arithmetic overflow (or underflow matter) , overflow count?

for easier understanding i'll using byte, same int or other basic integer type. imagine have value 240 , want add 24 it. arithmetic overflow. using checked keyword easy detect @ least ...

byte value = 240; try {     checked     {         value += 24;     } } catch (overflowexception e) {     // handle overflow, overflow count via % etc. } 

... throwing exception.

this using @ moment.

however, don't quite exception handling in one. exceptions pretty expensive, , want avoid them right start. me seems boneheaded-exception anyways. is there arithmetic wizardry detect upfront?

i guess check if difference between current value , maximum if large enough addition:

var difference = byte.maxvalue - value;  if(difference >= 24)//ok add 24 else//will cause overflow 

to detect underflows can use byte.minvalue value instead:

var difference = value - byte.minvalue; if(difference >= 24)//ok subtract 24 else//will cause underflow 

with these in mind go far making extension methods them:

public static class overflowextensions {     public static bool willadditionoverflow(this byte b, int val)     {         return byte.maxvalue - b < val;     }      public static bool willsubtractionunderflow(this byte b, int val)     {         return b - byte.minvalue < val;     } } 

which can use so:

using myapp.overflowextensions; //...  if(value.willadditionoverflow(24))     //value + 24 cause overflow  if(value.willsubtractionunderflow(24))     //value - 24 cause underflow 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -