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:
I found a workaround using Currency and doing the overflow math myself (and it turns out that VB6
Mod
operator also won't work onCurrency
):However, see Bob77's answer for a solution that is almost twice as fast as mine.