卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64334本站已运行4115

Kotlin 和 Golang 中的字符串散列

kotlin 和 golang 中的字符串散列

问题内容

在服务 a 中,我有一个像这样进行哈希处理的字符串:

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

我想在用 golang 编写的服务 b 中复制这段代码,因此对于同一个单词,我得到完全相同的哈希值。据我从 kotlin 文档中了解到,应用的哈希返回一个 64 位整数。所以在 go 中我这样做:

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

但是在进行单元测试时我没有得到相同的值。我得到:

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)
    }
}

结果:

7841672725449611742

我做错了什么吗?


正确答案


Java 以及 Kotlin 使用与 Go 不同的哈希函数。

可能的选项是:

  1. 使用标准哈希函数。
  2. 在 Go 中重新实现字符串的 Java hashCode。
卓越飞翔博客
上一篇: 错误:crypto/bcrypt:hashedPassword 不是给定密码的哈希值
下一篇: 在发生错误时省略 mongodb 事务回滚是一个好习惯吗
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏