D语言无符号字符串散列
D language unsigned hash of string
我是 D language 的初学者。
如何获得,作为 D 语言中的 uint
无符号 32 位整数,字符串的一些散列...
我需要一个快速而肮脏的哈希码(我不太关心 "randomness" 或 "lack of collision",我更关心性能)。
import std.digest.crc;
uint string_hash(string s) {
return crc320f(s);
}
不好...
(在 Linux/x86-64 上使用 gdc-5
和 phobos-2)
一个非常快的事情可能就是这样:
uint string_hash(string s) {
import std.digest.crc;
auto r = crc32Of(s);
return *(cast(uint*) r.ptr);
}
因为crc32Of
returns一个ubyte[4]
而不是你想要的uint
,所以需要转换,但是因为ubyte[4]
和uint
对机器来说是一样的,我们可以用那里看到的指针技巧做一个重新解释转换,在运行时免费转换类型。
虽然 Adams answer 完全符合您的要求,但您也可以使用 union 进行转换。
这是一个非常有用的技巧,所以不妨把它放在这里:
/**
* 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.
}
我是 D language 的初学者。
如何获得,作为 D 语言中的 uint
无符号 32 位整数,字符串的一些散列...
我需要一个快速而肮脏的哈希码(我不太关心 "randomness" 或 "lack of collision",我更关心性能)。
import std.digest.crc;
uint string_hash(string s) {
return crc320f(s);
}
不好...
(在 Linux/x86-64 上使用 gdc-5
和 phobos-2)
一个非常快的事情可能就是这样:
uint string_hash(string s) {
import std.digest.crc;
auto r = crc32Of(s);
return *(cast(uint*) r.ptr);
}
因为crc32Of
returns一个ubyte[4]
而不是你想要的uint
,所以需要转换,但是因为ubyte[4]
和uint
对机器来说是一样的,我们可以用那里看到的指针技巧做一个重新解释转换,在运行时免费转换类型。
虽然 Adams answer 完全符合您的要求,但您也可以使用 union 进行转换。 这是一个非常有用的技巧,所以不妨把它放在这里:
/**
* 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.
}