Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there utility methods for performing unsafe arithmetic in VB.NET?

I'm overriding getting a hash code. There's a point where

Hash = 1210600964 * 31 + -837896230

which causes an OverflowException. Is there a method that I can use, something like:

Hash = addUnsafe(multiplyUnsafe(1210600964, 31), -837896230)

Without needing to link my project to another assembly? I do not want to remove overflow checks. dllimports are OK.

like image 825
Joseph Nields Avatar asked Dec 31 '25 10:12

Joseph Nields


1 Answers

You can do the maths with 64-bit numbers instead and then use And to cut off any excess:

Option Infer On
' .....
Shared Function MultiplyWithTruncate(a As Integer, b As Integer) As Integer
    Dim x = CLng(a) * CLng(b)
    Return CInt(x And &HFFFFFFFF)
End Function

Although, as you can mix C# and VB.NET projects in one solution, it might be easiest to write a class in C# to do the unchecked arithmetic, even if you are not keen on adding a reference to another assembly.

It might even be a good idea to write the functions in C# too so that you can test that the VB functions return the expected values. It's what I did to check the above code.

Edit: I was prompted by Joseph Nields' comment to test for performance, and it turned out using CLng instead of Convert.ToInt64 and And works faster.

like image 191
Andrew Morton Avatar answered Jan 02 '26 01:01

Andrew Morton