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

元气小坏坏 提交于 2019-12-19 10:11:19

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/31436730/are-there-utility-methods-for-performing-unsafe-arithmetic-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!