修改后的FNV-1哈希算法的Go语言实现

huangapple go评论94阅读模式
英文:

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 (
	&quot;fmt&quot;
	&quot;hash/fnv&quot;
)

func main() {
	const MASK uint64 = 1&lt;&lt;63 - 1
	h := fnv.New64()
	h.Write([]byte(&quot;1133&quot;))
	hash := h.Sum64()
	fmt.Printf(&quot;%#x\n&quot;, MASK)
	fmt.Println(hash)
	hash = (hash &gt;&gt; 63) ^ (hash &amp; 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.

huangapple
  • 本文由 发表于 2015年10月23日 13:47:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/33295624.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定