문제

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

다른 팁

You will have to use 64 bit integers (they may be called Longs in your version of VB).

Dim Value1 As Long = 12345
Dim Value2 As Long = 67890
Dim Result As Long = Value1 + Value2

' Remove the overflow from the result
Console.WriteLine(Result AND &HFFFF)

You can use either signed or unsigned integers, but you will have to double your storage to make it work (e.g., 16 to 32).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top