开发者

Mimic C behavior - adding unsigned integers

开发者 https://www.devze.com 2023-01-24 02:03 出处:网络
In VB.NET the following code causes an overflow. Dim t As UInt64 t = UInt64.MaxValue t += 2UL It is my understanding that in C it \"wraps\". Assuming that is true开发者_Go百科, is there a way to mi

In VB.NET the following code causes an overflow.

    Dim t As UInt64
    t = UInt64.MaxValue
    t += 2UL

It is my understanding that in C it "wraps". Assuming that is true开发者_Go百科, is there a way to mimic this in Visual Basic? I need this for an implementation of UInt128 I am trying to write.


I don't know VB specifically (so you'll have to convert it yourself) but the usual way of doing this is:

def add (value,addval):
    if value <= maxvalue - addval:
        return value + addval
    subval = maxvalue - addval + 1
    return value - subval

It basically figures out in advance whether there will be overflow and turns an add(N) operation into an sub(maxvalue-N+1) one.

Both the test and the add/sub are safe within the range 0..maxvalue.


C# has the unchecked keyword that allows a specific scope to suppress overflow checking. In VB.NET there is a project wide setting. Check out this thread.

The project setting applies to the entire assembly. If that is not acceptable in your context you have to either create a separate assembly for unchecked functionality or use an approach like @paxdiablo's.

0

精彩评论

暂无评论...
验证码 换一张
取 消