【问题标题】:Why does this djb2 implementations loop terminate?为什么这个 djb2 实现循环终止?
【发布时间】:2019-04-08 07:58:02
【问题描述】:

字符串以单个空字节终止。既然一个 int 比一个 char 大,那么 int 怎么能变成 0 并一致地终止循环呢?

来源:http://www.cse.yorku.ca/~oz/hash.html

unsigned long
hash(unsigned char *str)
{
    unsigned long hash = 5381;
    int c;

    while (c = *str++)
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

    return hash;
}

【问题讨论】:

    标签: c


    【解决方案1】:

    从较小类型加载整数不会保留较小类型所没有的位;它们被清除(或通过符号扩展设置,对于有符号类型)。

    所以:

    int x = 0xfeefd00d;
    x = (char) 1;
    

    将值1 作为整数保留在x 中,不是 0xfeedf001

    【讨论】:

      【解决方案2】:

      当一个变量在表达式中与不同类型的变量一起使用时(例如在循环条件中的赋值),就会产生一个implicit conversion。转换仅在类型之间进行转换,但如果可能,会保留该值。

      因此,当您到达str 中的空终止符时,它会被转换(实际上是promoted)为int,并保持值0。而0 始终为“false”,从而结束循环。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-10
        • 1970-01-01
        • 2016-08-22
        • 1970-01-01
        • 2018-10-02
        • 2019-09-09
        相关资源
        最近更新 更多