Java objects have a hashCode
, which are cheaper than a cryptographic hash. How would one implement such a hashCode in Go?
在Go中计算hashCode
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答
- doulu8341 2016-09-05 13:25关注
The Go programming language is open source. You can check its standard library for a fast and efficient Go hash implementation.
Here it is:
runtime/hash64.go
for 64-bit architectureruntime/hash32.go
for 32-bit architecture
They are unexported, but if you'd ever need them in your app, you can just copy the code to your project. Also note that if your CPU supports it, the Go runtime will use
aeshash
to utilize your CPU's capabilities (more info on this here: How does go calculate a hash value for keys in a map?).Qutoing the shorter 32-bit version:
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)) }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 微信会员卡接入微信支付商户号收款
- ¥15 如何获取烟草零售终端数据
- ¥15 数学建模招标中位数问题
- ¥15 phython路径名过长报错 不知道什么问题
- ¥15 深度学习中模型转换该怎么实现
- ¥15 HLs设计手写数字识别程序编译通不过
- ¥15 Stata外部命令安装问题求帮助!
- ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
- ¥15 TYPCE母转母,插入认方向
- ¥15 如何用python向钉钉机器人发送可以放大的图片?