String hashing in Kotlin and Golang

WBOY
Release: 2024-02-06 10:12:12
forward
670 people have browsed it

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
}
Copy after login

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)
}
Copy after login

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)
    }
}
Copy after login

result:

7841672725449611742
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!