[英]Const expressions in C - How to hash a string?
我正在創建一個內核模塊。 在這個模塊中,我需要檢查一些預定義字符串的輸入。 在C ++中,可以創建一個constexpr函數,用於在編譯時計算哈希值。 我正在尋找一種方法來做到這一點。
一些使用Jenkins哈希函數的偽代碼:
u32 hash(const char *key)
{
u32 hash, i;
size_t len;
len = strlen(key);
for(hash = i = 0; i < len; ++i)
{
hash += key[i];
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
return hash;
}
const u32 myStringList [] = {
hash("hello"),
hash("this is a text"),
hash("good morning")
};
int findString(const char * searchStr) {
u32 h;
int i;
h = hash(searchStr);
for (i = 0; i < sizeof(myStringList)/sizeof(const u32); i++) {
if (h == myStringList[i]) return i;
}
return -1;
}
如何修改才能搞定?
我不認為你可以,C沒有constexpr
或編譯時評估。 這就是為什么許多人轉向預處理器(在C ++中不經常使用)的原因,但使用它的字符串處理(與字符串“構造”相對)並不容易。
有時這可以通過添加另一個預處理步驟來解決,也許使用一些更高級的語言(我更喜歡Python)來構建所需的C代碼。
如果這不是一個選項,那么我只是在啟動期間初始化哈希表一次。 如果您沒有顯式的init函數(我相信Linux內核模塊可以),您當然可以使用靜態標志:
static const char *strings[] = { "hello", "this is a text", "good morning", NULL };
static uint32_t myStringList[(sizeof strings / sizeof *strings) - 1];
void something(const char *string)
{
static bool hash_initialized = false;
if(!hash_initialized)
{
for(size_t i = 0; strings[i] != NULL; ++i)
myStringList[i] = hash(strings[i]);
hash_initialized = true;
}
if(hash_lookup(string))
{
...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.