C 如果将无符号长按位运算的结果与 0 进行比较的条件被评估为假,尽管预期为真(0 == 0 为假)

C if condition comparing result of unsigned long bitwise operation with 0 is evaluated as false although true expected ( 0 == 0 is false)

versionNumberAndPlaceNumber0xFFFF00以下if的真实情况未输入:

if(versionNumberAndPlaceNumber & 0xFFUL == 0UL) {

为什么会这样?

.

下面是一段较长的代码摘录:

if(bytes_received == 27) {      // the data size of "struct bee" (padded), version number (8 bits) and place number of struct place
printf("\n27\n");
                unsigned long versionNumberAndPlaceNumber = 0;
                memcpy(&versionNumberAndPlaceNumber, &(read[24]), 8);     // read 8 = sizeof(long) on x64 bytes, hope it's faster than transferring less bytes on x64 (into possibly a register)
                /* memcpy copies bytes from increasing source address to increasing destination address, x64 this is supposed to run on is Little Endian thus for example [0xFF, 0x00, ...] as an unsigned long is ...0000000011111111 = 255 */
printf("\n%lu\n", versionNumberAndPlaceNumber);
                if(versionNumberAndPlaceNumber & 0xFFUL == 0UL) {          // version 0 of data for version 0 of this server
printf("\nv correct\n");
                    unsigned long location[3];

(注意读取缓冲区为32字节。)

这是输出:

27

16776960

.

调试中:

而不是打印 versionNumberAndPlaceNumber 我还打印了整个 if 条件(指示 %d 而不是 %lu)并得到 0 作为输出因此条件似乎是错误的。

但是 16776960 = 0xFFFF000xFFFF00 AND 0xFF0.

为什么是0 == 0false

== 运算符的优先级高于 &(按位与),因此您的条件等于此

if(versionNumberAndPlaceNumber & (0xFFUL == 0UL)) // 0xFFFF00 & 0 -> 0 -> false

Operator precedence 描述操作发生的顺序。这与数学中的 PEMDAS 相同 class 并且是为了减少所需的括号数量。 == 运算符的优先级为 9,& 的优先级为 10,因此 == 运算符首先获取其参数。

这意味着 (a & b == c)(a & (b == c)) 相同,这不是您所期望的。