我是D语言的初学者.
如何得到,作为uintD语言中的无符号32位整数,字符串的一些哈希...
我需要一个快速而又脏的哈希码(我不太关心"随机性"或"缺乏冲突",我更关心性能).
import std.digest.crc;
uint string_hash(string s) {
return crc320f(s);
}
Run Code Online (Sandbox Code Playgroud)
不好......
(gdc-5在带有phobos-2的Linux/x86-64上使用)
虽然亚当斯的回答完全符合您的要求,但您也可以使用联合来进行投射.这是一个非常有用的技巧,所以可以把它放在这里:
/**
* 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.
}
Run Code Online (Sandbox Code Playgroud)
一个非常快的事情可能就是这样:
uint string_hash(string s) {
import std.digest.crc;
auto r = crc32Of(s);
return *(cast(uint*) r.ptr);
}
Run Code Online (Sandbox Code Playgroud)
因为crc32Of返回a ubyte[4]而不是uint你想要的,所以转换是必要的,但是由于ubyte[4]并且uint与机器是相同的,我们可以只使用在那里看到的指针技巧进行重新解释转换以在运行时免费转换类型.
| 归档时间: |
|
| 查看次数: |
152 次 |
| 最近记录: |