我是D语言的完全初学者。
如何以D语言中的uint无符号32位整数的形式获得字符串的散列.
我需要一个快速而肮脏的哈希代码(我不太关心“随机性”或“缺乏冲突”,我更关心的是性能)。
import std.digest.crc;
uint string_hash(string s) {
return crc320f(s);
}不好..。
(在Linux/x86-64和Phobos-2上使用gdc-5 )
发布于 2015-07-23 18:28:13
一件非常迅速的事情可能就是这样:
uint string_hash(string s) {
import std.digest.crc;
auto r = crc32Of(s);
return *(cast(uint*) r.ptr);
} 由于crc32Of返回一个ubyte[4]而不是您想要的uint,所以转换是必要的,但是由于ubyte[4]和uint对机器来说是一样的,所以我们只需重新解释一下在运行时将类型转换为免费的指针技巧。
发布于 2015-07-24 07:47:43
亚当斯的回答做的正是你想要的,你也可以用联盟来做铸造。这是一个非常有用的技巧,所以不妨把它放在这里:
/**
* Returns a crc32Of hash of a string
* Uses a union to store the ubyte[]
* And then simply reads that memory as a uint
*/
uint string_hash(string s){
import std.digest.crc;
union hashUnion{
ubyte[4] hashArray;
uint hashNumber;
}
hashUnion x;
x.hashArray = crc32Of(s); // stores the result of crc32Of into the array.
return x.hashNumber; // reads the exact same memory as the hashArray
// but reads it as a uint.
}https://stackoverflow.com/questions/31594880
复制相似问题