首頁  >  文章  >  後端開發  >  Kotlin 和 Golang 中的字串雜湊

Kotlin 和 Golang 中的字串雜湊

WBOY
WBOY轉載
2024-02-06 10:12:12646瀏覽

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。

以上是Kotlin 和 Golang 中的字串雜湊的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除