VB6如何获得类似C的整数溢出 [英] VB6 how to get C-like integer overflow
问题描述
我想将这个简单的散列算法移植到VB6中。
公共函数simpleHash(hashString As String)As Long
Dim hash As Long
Dim c As Long
Dim i As Integer
On Local Error Resume Next
hash = 5381
For i = 1 To Len(hashString)
c = AscW(Mid $(hashString,i,1))
hash = hash * 33 + c
Next i
simpleHash = hash
End Function
问题是,尽管我的 我该如何解决这个问题或者以不同的方式实施这个算法? On Error
语句会抑制错误6:溢出异常,如果发生溢出,变量
hash
不会再更新。 p>
虽然我找不到任何 djb2 的测试向量来验证我自己的实现,它似乎运行得非常快:
私有类型CURRENCY_CURRENCY
值作为货币
结束类型
私有类型CURRENCY_2LONGS
ValueLo As Long
ValueHi As Long
结束类型
Public Function djb2(ByVal StringToHash As String)As Long
Dim C2L As CURRENCY_2LONGS
Dim CC As CURRENCY_CURRENCY
Dim I As Long
C2L.ValueLo = 5381
For I = 1 To Len(StringToHash)
LSet CC = C2L
CC.Value = CC.Value * 33 @ + CCur(AscW(Mid $(StringToHash,I,1)) )/ 10000 @
LSet C2L = CC
C2L.ValueHi = 0
下一个I
djb2 = C2L.ValueLo
结束函数
I want to port this simple hash algorithm to VB6.
I have come up with:
Public Function simpleHash(hashString As String) As Long
Dim hash As Long
Dim c As Long
Dim i As Integer
On Local Error Resume Next
hash = 5381
For i = 1 To Len(hashString)
c = AscW(Mid$(hashString, i, 1))
hash = hash * 33 + c
Next i
simpleHash = hash
End Function
The problem is, despite my On Error
statement which suppresses the Error 6: Overflow exceptions, the variable hash
is not updated any more if an overflow occurs.
How can I fix that or implement this algorithm differently?
I would question whether it makes sense to hash UTF-16LE ("Unicode") this way. It might make a lot more sense to convert your VB String to UTF-8 and then hash that.
While I can't find any test vectors for djb2 to validate my own implementation it seems to run quite quickly:
Private Type CURRENCY_CURRENCY
Value As Currency
End Type
Private Type CURRENCY_2LONGS
ValueLo As Long
ValueHi As Long
End Type
Public Function djb2(ByVal StringToHash As String) As Long
Dim C2L As CURRENCY_2LONGS
Dim CC As CURRENCY_CURRENCY
Dim I As Long
C2L.ValueLo = 5381
For I = 1 To Len(StringToHash)
LSet CC = C2L
CC.Value = CC.Value * 33@ + CCur(AscW(Mid$(StringToHash, I, 1))) / 10000@
LSet C2L = CC
C2L.ValueHi = 0
Next I
djb2 = C2L.ValueLo
End Function
这篇关于VB6如何获得类似C的整数溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!