gpt4 book ai didi

C 对按位移位操作感到困惑

转载 作者:行者123 更新时间:2023-11-30 21:46:10 26 4
gpt4 key购买 nike

在我正在读的一本书中,有一个哈希函数如下所示

static inline ulong zend_inline_hash_func(const char *arKey, uint nKeyLength)
{
register ulong hash = 5381;

for (uint i = 0; i < nKeyLength; ++i) {
hash = ((hash << 5) + hash) + arKey[i];
}
return hash;
}

The hash << 5 + hash expression is the same as hash * 32 + hash or just hash * 33.

我明白为什么hash << 5 + hashhash * 32 + hash 相同,但是它怎么变成了hash * 33是我不明白的。我试图推理hash * 32溢出并换行成为模 2^n 运算,但显然这不是因为 a) hash类型为ulong它足够大,可以容纳 hash *32 的结果表达。 b) 偶数unint仍然很大,容易被所讨论的乘法溢出有更多 C 知识的人可以帮我做一个简单的解释,甚至可以指出我困惑的根源。谢谢。

最佳答案

这与 C 关系不大,而与数学关系更大。

The hash << 5 + hash expression is the same as hash * 32 + hash or just hash * 33.

基本代数表明这些事情是正确的(这些是用 C 编写的):

/* #1 */ (a * b + a * c) == (a * (b + c))
/* #2 */ (a) == (a * 1)

应用#2,我们可以说:

(hash * 32 + hash) == (hash * 32 + hash * 1)

现在应用#1,我们可以发现:

(hash * 32 + hash * 1) == (hash * (32 + 1))

这可以简化为:

hash * 33

这是基础数学,但也许您累了或劳累过度,只是看不出它是如何工作的:)

关于C 对按位移位操作感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44019819/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com