亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Go 中計算 hashCode

在 Go 中計算 hashCode

Go
郎朗坤 2022-03-07 22:22:54
Java 對象有一個hashCode,它比加密哈希便宜。如何在 Go 中實現這樣的 hashCode?
查看完整描述

1 回答

?
大話西游666

TA貢獻1817條經驗 獲得超14個贊

Go 編程語言是開源的。你可以查看它的標準庫,了解快速高效的 Go 哈希實現。


這里是:


runtime/hash64.go對于 64 位架構


runtime/hash32.go用于 32 位架構


它們未導出,但如果您在應用程序中需要它們,您只需將代碼復制到您的項目中即可。另請注意,如果您的 CPU 支持它,Go 運行時將使用aeshash您的 CPU 的功能(更多信息請點擊此處:Go 如何計算地圖中鍵的哈希值?)。


引用較短的32 位版本:


const (

    // Constants for multiplication: four random odd 32-bit numbers.

    m1 = 3168982561

    m2 = 3339683297

    m3 = 832293441

    m4 = 2336365089

)


func memhash(p unsafe.Pointer, seed, s uintptr) uintptr {

    if GOARCH == "386" && GOOS != "nacl" && useAeshash {

        return aeshash(p, seed, s)

    }

    h := uint32(seed + s*hashkey[0])

tail:

    switch {

    case s == 0:

    case s < 4:

        h ^= uint32(*(*byte)(p))

        h ^= uint32(*(*byte)(add(p, s>>1))) << 8

        h ^= uint32(*(*byte)(add(p, s-1))) << 16

        h = rotl_15(h*m1) * m2

    case s == 4:

        h ^= readUnaligned32(p)

        h = rotl_15(h*m1) * m2

    case s <= 8:

        h ^= readUnaligned32(p)

        h = rotl_15(h*m1) * m2

        h ^= readUnaligned32(add(p, s-4))

        h = rotl_15(h*m1) * m2

    case s <= 16:

        h ^= readUnaligned32(p)

        h = rotl_15(h*m1) * m2

        h ^= readUnaligned32(add(p, 4))

        h = rotl_15(h*m1) * m2

        h ^= readUnaligned32(add(p, s-8))

        h = rotl_15(h*m1) * m2

        h ^= readUnaligned32(add(p, s-4))

        h = rotl_15(h*m1) * m2

    default:

        v1 := h

        v2 := uint32(seed * hashkey[1])

        v3 := uint32(seed * hashkey[2])

        v4 := uint32(seed * hashkey[3])

        for s >= 16 {

            v1 ^= readUnaligned32(p)

            v1 = rotl_15(v1*m1) * m2

            p = add(p, 4)

            v2 ^= readUnaligned32(p)

            v2 = rotl_15(v2*m2) * m3

            p = add(p, 4)

            v3 ^= readUnaligned32(p)

            v3 = rotl_15(v3*m3) * m4

            p = add(p, 4)

            v4 ^= readUnaligned32(p)

            v4 = rotl_15(v4*m4) * m1

            p = add(p, 4)

            s -= 16

        }

        h = v1 ^ v2 ^ v3 ^ v4

        goto tail

    }

    h ^= h >> 17

    h *= m3

    h ^= h >> 13

    h *= m4

    h ^= h >> 16

    return uintptr(h)

}


// Note: in order to get the compiler to issue rotl instructions, we

// need to constant fold the shift amount by hand.

// TODO: convince the compiler to issue rotl instructions after inlining.

func rotl_15(x uint32) uint32 {

    return (x << 15) | (x >> (32 - 15))

}



查看完整回答
反對 回復 2022-03-07
  • 1 回答
  • 0 關注
  • 310 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號