一位矿山的同事用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所有计算都是同步的,直到在Java中的计算得到"-1413090664“,而在VBA中得到"50126516888”的字母"n“为止。问题是,在Java中,由于result被定义为int,因此它不能容纳最多11位数,从而导致负数。
注意:我知道我可以将Java代码改为使用double,但是我不能这样做。我在找VB的解决方案。
我需要尽可能多地模拟Int32代码,所以我需要VBA代码来模拟未经检查的Int32溢出。如何才能做到这一点?
发布于 2016-04-26 10:56:04
不可能禁用溢出检查,但是可以通过使用两个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算法派生出来的散列。
https://stackoverflow.com/questions/36849764
复制相似问题