[英]Merging few ints into unsigned long long(64 bit) with bitwise operators
[英]Bitwise operators on unsigned long?
我目前正在使用這樣的哈希函數:
unsigned long hashFunc(const char *str, unsigned int tablesize ) // djb2 hash
{
unsigned long hash = 5381;
int c;
while (c = *str++)
hash = ((hash << 5) + hash)+ c; /* hash * 33 + c */
return (hash & tablesize)-1;
}
但是,顯然,按位運算符&對於某些長值會失敗,而是返回long的最大值。 例如,對表大小為63的單詞“ care”進行散列將返回0xffffffff。
難道位運算符不打算用於無符號長整數嗎? 如果是這樣,我還有什么其他選擇?
您需要在括號內加上“ -1”:
return (hash & (tablesize - 1));
僅當已知tablesize為2的冪時才有效。
如果tablesize不是2的冪,則應該使用模運算符“%”:
return hash % tablesize;
(在這種情況下,不需要“ -1”)。
兩種類型unsigned int
和unsigned long
可能具有不同的大小,這可能會導致按位操作執行您未預期的操作。 嘗試投射:
return (hash & (unsigned long)tablesize)-1;
(或者,如果您堅持要使用static_cast
)
我對其進行了一點測試,看來效果很好。 簡而言之,很不幸- ("care",63)
的hash
值為0x17c9504c0
,當您執行二進制運算時-和0x3f
得到純0。減去1則得到0xffffffffffffffff
。
問題出在您的代碼中,而不是機器中:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.