VBA hash string

前端 未结 4 802
无人共我
无人共我 2020-12-12 17:41

How do I get a short hash of a long string using Excel VBA

Whats given

  • Input string is not longer than 80 characters
  • Valid in
4条回答
  •  独厮守ぢ
    2020-12-12 18:14

    32 bits hash function for strings with a low level of collision:

    Public Function StrHash(text As String) As Long
        Dim i As Long
        StrHash = &H65D5BAAA
    
        For i = 1 To Len(text)
            StrHash = ((StrHash + AscW(Mid$(text, i, 1))) Mod 69208103) * 31&
        Next
    End Function
    

    Or as a 64 bits hash function:

    Public Function StrHash64(text As String) As String
        Dim i&, h1&, h2&, c&
        h1 = &H65D5BAAA
        h2 = &H2454A5ED
    
        For i = 1 To Len(text)
            c = AscW(Mid$(text, i, 1))
            h1 = ((h1 + c) Mod 69208103) * 31&
            h2 = ((h2 + c) Mod 65009701) * 33&
        Next
    
        StrHash64 = Right("00000000" & Hex(h1), 8) & Right("00000000" & Hex(h2), 8)
    End Function
    

    Based on the FNV hash algorithm

提交回复
热议问题