go_boost_hashcode
项目中遇到旧的C++代码采用boost对方法名取哈希值并存入数据库中.新项目使用GO实现需要对方法名做同样的哈希取值.所以就有了下文:
Boost 获取字符串哈希值
http://www.boost.org/doc/libs/1_47_0/doc/html/hash.html
boost::hash<std::string> string_hash;
std::size_t h = string_hash("Hash me");
C++ 代码演示 boost hashcode获取逻辑
#include <iostream>
#include <string.h>
#include <hash.hpp>
#include <stdio.h>
int main()
{
std::string st = "get_t_user_info";
// Using Boost Library
boost::hash<std::string> hash_fn;
std::size_t code = hash_fn("get_t_user_info");
printf("%s %ld %u\n", st.c_str(), code, (unsigned short)code);
// Get Same Result Without Boost Library
std::size_t seed = 0;
for(std::string::iterator it = st.begin(); it != st.end(); ++it)
{
seed ^= size_t(*it) + 0x9e3779b9 + (seed<<6) + (seed>>2);
printf("-- %ld %d\n", seed, *it);
}
printf("%s %ld %u\n", st.c_str(), seed, (unsigned short)seed);
}
- Run
GO 代码实现 boost 哈希值获取
package main
import (
"fmt"
)
func main() {
st := "get_t_user_info"
var seed uint64 = 0
var magicNumber uint64 = 0x9e3779b9
for _, s := range st {
seed ^= uint64(s) + magicNumber + (seed << 6) + (seed >> 2)
fmt.Println("--", seed, s)
}
fmt.Println(st, seed, uint16(seed))
}
- Run