【问题标题】:bit representation of unsigned int zero无符号整数零的位表示
【发布时间】:2014-08-31 06:45:46
【问题描述】:

在无符号整数上使用按位运算时,我遇到了一种我没想到的行为。我将直接进入我的示例。

unsigned int a = 0;
unsigned int b = 0;
std::printf("a & b: %u\n", a & b);
std::printf("a == b: %i\n", a == b);
std::printf("a & b == a: %i\n", a & b == a);

以上代码产生以下输出:

a & b: 0
a == b: 1
a & b == a: 0

最后一行让我感到困惑。 a & b == a 不应该评估为 true,因为 a & b == (unsigned int)0a == (unsigned int)0

【问题讨论】:

标签: c++ bit-manipulation unsigned


【解决方案1】:

您遇到这种行为是因为您没有意识到 ==C operator precedence table 中位于 & 之前。事实上,一个好的编译器会立即警告你的代码:

t.cpp:10:35: warning: & has lower precedence than ==; == will be evaluated first [-Wparentheses]
std::printf("a & b == a: %i\n", a & b == a);
                                  ^~~~~~~~
t.cpp:10:35: note: place parentheses around the '==' expression to silence this warning
std::printf("a & b == a: %i\n", a & b == a);
                                  ^
                                    (     )
t.cpp:10:35: note: place parentheses around the & expression to evaluate it first
std::printf("a & b == a: %i\n", a & b == a);
                                  ^
                                (    )

确保您的警告已开启,例如g++ -Wall -Wextra -Werror

【讨论】:

    【解决方案2】:

    你应该写:

    (a & b) == a 
    

    现在你会得到 1,因为 a & b will be evaluated first

    (a & b) = 00 == 0 是 1。

    在您的情况下,a & b == a 被评估为 a & (b == a)b == a 为 1,a & 1 为 0。

    【讨论】:

      【解决方案3】:

      由于=='s precedence over &a & b == a 被评估为a & (b == a)(而不是您似乎预期的(a & b) == a)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-31
        • 2012-07-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多