英文:
Modified FNV-1 hash algorithm in golang
问题
本地库使用了FNV-1哈希算法https://golang.org/pkg/hash/fnv/,它返回一个uint64值(范围:0到18446744073709551615)。
我需要将这个值存储在PostgreSQL的bigserial中,但它的范围是1到9223372036854775807。
有可能将哈希大小更改为例如56吗?http://www.isthe.com/chongo/tech/comp/fnv/index.html#xor-fold
有人可以帮助更改本地算法以生成56位哈希吗?
https://golang.org/src/hash/fnv/fnv.go
更新
我自己做到了,使用了这个文档http://www.isthe.com/chongo/tech/comp/fnv/index.html#xor-fold
package main
import (
"fmt"
"hash/fnv"
)
func main() {
const MASK uint64 = 1<<63 - 1
h := fnv.New64()
h.Write([]byte("1133"))
hash := h.Sum64()
fmt.Printf("%#x\n", MASK)
fmt.Println(hash)
hash = (hash >> 63) ^ (hash & MASK)
fmt.Println(hash)
}
http://play.golang.org/p/j7q3D73qqu
这样正确吗?
英文:
Native library has FNV-1 hash algorithm https://golang.org/pkg/hash/fnv/ that returns uint64 value (range: 0 through 18446744073709551615).
I need to store this value in PostgreSQL bigserial, but it's range is 1 to 9223372036854775807.
It is possible to change hash size to eg. 56?http://www.isthe.com/chongo/tech/comp/fnv/index.html#xor-fold
Can someone help to change native algorithm to produce 56 bit hashes?
https://golang.org/src/hash/fnv/fnv.go
Update
Did it myself using this doc http://www.isthe.com/chongo/tech/comp/fnv/index.html#xor-fold
<!-- language: lang-go -->
package main
import (
"fmt"
"hash/fnv"
)
func main() {
const MASK uint64 = 1<<63 - 1
h := fnv.New64()
h.Write([]byte("1133"))
hash := h.Sum64()
fmt.Printf("%#x\n", MASK)
fmt.Println(hash)
hash = (hash >> 63) ^ (hash & MASK)
fmt.Println(hash)
}
http://play.golang.org/p/j7q3D73qqu
Is it correct?
答案1
得分: 3
是的,这是一个正确的将XOR折叠到63位的方法。但是还有一种更简单的方法:
hash = hash % 9223372036854775808
XOR折叠的分布是可疑的,可能在某个地方已经被证明,但不是立即显而易见的。然而,取模运算明显是将哈希算法的分布包装到较小的值域中。
英文:
> Is it correct?
Yes, it's a correct XOR-folding to 63 bits. But there's a much easier way:
hash = hash % 9223372036854775808
The distribution of XOR-folding is dubious, probably proven somewhere but not immediately obvious. Modulo, however, is clearly a wrapping of the hash algo's distribution to a smaller codomain.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论