美文网首页程序员
boost 字符串hashcode 逻辑和用go实现

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

作者: 肚腩照明月 | 来源:发表于2018-03-19 11:22 被阅读0次

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
    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
    01.jpg

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

相关文章

网友评论

    本文标题:boost 字符串hashcode 逻辑和用go实现

    本文链接:https://www.haomeiwen.com/subject/libuqftx.html