boost 字符串hashcode 逻辑和用go实现

go_boost_hashcode

项目中遇到旧的C++代码采用boost对方法名取哈希值并存入数据库中.新项目使用GO实现需要对方法名做同样的哈希取值.所以就有了下文:

Boost 获取字符串哈希值

http://www.boost.org/doc/libs/1_47_0/doc/html/hash.html

boost::hash string_hash;
std::size_t h = string_hash("Hash me");

C++ 代码演示 boost hashcode获取逻辑

#include  
#include 
#include  
#include   
int main()
{
    std::string st = "get_t_user_info";

    // Using Boost Library
    boost::hash 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
    boost 字符串hashcode 逻辑和用go实现_第1张图片
    02.jpg

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
    boost 字符串hashcode 逻辑和用go实现_第2张图片
    01.jpg

源码在: https://github.com/toniz/go_boost_hashcode

你可能感兴趣的:(boost 字符串hashcode 逻辑和用go实现)