在Kotlin和Golang中对字符串进行哈希处理。

huangapple go评论101阅读模式
英文:

String Hashed in both Kotlin and Golang

问题

在服务A中,我有一个字符串,它的哈希值计算如下:

  1. fun String.toHash(): Long {
  2. var hashCode = this.hashCode().toLong()
  3. if (hashCode < 0L) {
  4. hashCode *= -1
  5. }
  6. return hashCode
  7. }

我想在使用Golang编写的服务B中复制这段代码,以便对于相同的单词,我可以得到完全相同的哈希值。根据我对Kotlin文档的理解,应用的哈希函数返回一个64位整数。所以在Go中,我这样做:

  1. func hash(s string) int64 {
  2. h := fnv.New64()
  3. h.Write([]byte(s))
  4. v := h.Sum64()
  5. return int64(v)
  6. }

但是,在对此进行单元测试时,我得不到相同的值。我得到的结果是:

  1. func Test_hash(t *testing.T) {
  2. tests := []struct {
  3. input string
  4. output int64
  5. }{
  6. {input: "papafritas", output: 1079370635},
  7. }
  8. for _, test := range tests {
  9. got := hash(test.input)
  10. assert.Equal(t, test.output, got)
  11. }
  12. }

结果是:

  1. 7841672725449611742

我做错了什么吗?

英文:

In service A I have a string that get hashed like this:

  1. fun String.toHash(): Long {
  2. var hashCode = this.hashCode().toLong()
  3. if (hashCode &lt; 0L) {
  4. hashCode *= -1
  5. }
  6. return hashCode
  7. }

I want to replicate this code in service B written in Golang so for the same word I get the exact same hash. For what I understand from Kotlin's documentation the hash applied returns a 64bit integer. So in Go I am doing this:

  1. func hash(s string) int64 {
  2. h := fnv.New64()
  3. h.Write([]byte(s))
  4. v := h.Sum64()
  5. return int64(v)
  6. }

But while unit testing this I do not get the same value. I get:

  1. func Test_hash(t *testing.T) {
  2. tests := []struct {
  3. input string
  4. output int64
  5. }{
  6. {input: &quot;papafritas&quot;, output: 1079370635},
  7. }
  8. for _, test := range tests {
  9. got := hash(test.input)
  10. assert.Equal(t, test.output, got)
  11. }
  12. }

Result:

  1. 7841672725449611742

Am I doing something wrong?

答案1

得分: 3

Java和因此Kotlin使用的哈希函数与Go不同。

可能的选项有:

  1. 使用标准的哈希函数。
  2. 在Go中重新实现Java字符串的hashCode函数。
英文:

Java and therefore Kotlin uses different hash function than Go.

Possible options are:

  1. Use a standard hash function.
  2. Reimplement Java hashCode for Strings in Go.

huangapple
  • 本文由 发表于 2023年2月7日 03:42:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75365845.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定