Home >Backend Development >Golang >String hashing in Kotlin and Golang

String hashing in Kotlin and Golang

WBOY
WBOYforward
2024-02-06 10:12:12701browse

Kotlin 和 Golang 中的字符串散列

Question content

In service a, I have a string that is hashed like this:

fun string.tohash(): long {
    var hashcode = this.hashcode().tolong()
    if (hashcode < 0l) {
        hashcode *= -1
    }
    return hashcode
}

I want to replicate this code in service b written in golang, so for the same word I get the exact same hash. As far as I understand from the kotlin documentation, the applied hash returns a 64-bit integer. So in go I do this:

func hash(s string) int64 {
    h := fnv.new64()
    h.write([]byte(s))
    v := h.sum64()
    return int64(v)
}

But I don't get the same value when doing unit testing. I get:

func test_hash(t *testing.t) {
    tests := []struct {
        input  string
        output int64
    }{
        {input: "papafritas", output: 1079370635},
    }
    for _, test := range tests {
        got := hash(test.input)
        assert.equal(t, test.output, got)
    }
}

result:

7841672725449611742

Did I do something wrong?


Correct answer


Java and Kotlin use different hash functions than Go.

Possible options are:

  1. Use standard hash functions.
  2. Reimplement Java hashCode for strings in Go.

The above is the detailed content of String hashing in Kotlin and Golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete