如何模拟Int32溢出?

时间:2016-04-25 19:48:19

标签: java excel vba excel-vba

一位矿工的同事用Java开发了一些用Java做一些简单计算的东西。我正在将代码转换为VBA,但我意识到,一旦计算结果为11位或更多,计算就会失去同步。

Java代码

int prime = 31;
int result = 1;
String test = "Periwinkle"

for (char c : test.toCharArray()) {
 result = prime * result + Character.getNumericValue(c);
 System.out.println("letter " + c + " number " + Character.getNumericValue(c));
 System.out.println(result + " from " + c);
}
 System.out.println(Math.abs(result));

VBA代码

Dim arr As Variant
Dim letr As String
Dim num As Integer
Dim result, prime As Integer

For Each cell In Range("A1") 'A1 = Periwinkle
    result = 1
    prime = 31
    arr = CharacterArray(cell.value)
 For Each element In arr
    letr = element
    'Debug.Print "Letter: " & letr
    num = getNumber(letr)
    'Debug.Print "Number: " & num
    result = prime * result + num
    'Debug.Print "Result: " & result
    Cells(cell.Row, 3).value = Math.Abs(result)
 Next
Next

所有的计算都是同步的,直到字母" n"其中Java中的计算结果为" -1413090664"而在VBA中的结果是" 50126516888"。问题是在Java中,result被定义为int,它不能容纳11位数,从而导致负数。

注意:我知道我可以将Java代码更改为使用double,但我无法进行此更改。我正在寻找VB的解决方法。

我需要尽可能多地模仿Java代码,所以我需要VBA代码来模拟未经检查的Int32溢出。怎么办呢?

1 个答案:

答案 0 :(得分:1)

无法禁用溢出检查,但可以通过使用两个int32来避免它。 这个VBA函数会得到完全相同的结果:

Sub Usage()
  Debug.Print Hash("Periwinkle")
End Sub

Public Function Hash(text As String) As Long
  Dim lo&, hi&, i%
  lo = 1
  For i = 1 To Len(text)
    lo = 31& * (lo And 65535) + GetNumericValue(AscW(Mid$(text, i, 1)))
    hi = 31& * (hi And 65535) + (lo \ 65536)
  Next
  Hash = Abs((lo And 65535) + (hi And 32767) * 65536 + (&H80000000 And -(hi And 32768)))
End Function

Private Function GetNumericValue(ByVal c As Integer) As Integer
  Select Case c
    Case 48 To 57:   GetNumericValue = c - 48  '[0-9]'
    Case 65 To 90:   GetNumericValue = c - 55  '[A-Z]'
    Case 97 To 122:  GetNumericValue = c - 87  '[a-z]'
    Case 188 To 190: GetNumericValue = -2
    Case 178:        GetNumericValue = 2
    Case 179:        GetNumericValue = 3
    Case 185:        GetNumericValue = 1
    Case Else:       GetNumericValue = -1
  End Select
End Function

请注意,Java代码正在计算从FNV算法派生的哈希值。