I'm working on a vb.net app that needs to add multiple integers together. The integers are to be unsigned, and 32 bits in length.
It is expected that the integers will be so large that they will overflow when addition takes place. If any overflow does occur, I don't want to store any of the overflow, or there to be any exceptions that occur.
For example, If I was working with 4 bit numbers, I would want the following behaviour:
1111 + 0010 = 0001
I've tried the following to see what happens on an overflow - I get an overflow exception. Is there any elegant way around this?
Dim test As UInt32 = UInt32.MaxValue
Console.WriteLine(test.ToString())
test = test + 1
Console.WriteLine(test.ToString())
I'm currently using UInt32 to represent the integers, however this can be changed if somebody knows a better type.
It's important that the overflow bits are not stored, as later on I will want to perform bit shifts, etc on these numbers.
I can see the obvious solution of converting between UInt64 and UInt32, however I may have to expand the app in the future to use 64 bit numbers (so it would be nice to have a solution that's easily expandable)
Thanks in advance,
Dave
You can use the "Remove integer overflow checks" option in "Project" -> "<project name> Properties..." -> "Compile" tab -> "Advanced Compile Options..."
Dim a As UInt32 = UInt32.MaxValue
a += 1
Console.WriteLine(a) ' outputs 0