Checking for arithmetic overflow in C# .NET

Exercises in .NET with Andras Nemes

As you know primitive numeric types in C# – and other modern programming languages – have maximum and minimum values that can be stored in memory. If you’re trying to store a larger number in the variable then you’ll get an overflow with unexpected results.

Let’s see an example with the “byte” type. It is actually not one of the primitive types, like int or long, but simply a keyword for an integral type to store the numbers 0-255. Why 255? 1 byte consists of 8 bits and 8 bits in the computer’s memory allows us to store 255 as the highest number. 255 in binary is all 1’s for all 8 bits:

11111111

What happens if we add 1 to that? On paper we can easily solve it by some basic binary maths:

11111111
+ 00000001
===========
100000000

View original post 194 more words

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.