简体   繁体   English

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)

versionNumberAndPlaceNumber being 0xFFFF00 the true case of the following if is not entered: versionNumberAndPlaceNumber0xFFFF00以下if的真实情况未输入:

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

Why would this be?为什么会这样?

. .

Here follows a longer code excerpt:下面是一段较长的代码摘录:

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];

(Note the read buffer is 32 bytes.) (注意读取缓冲区为 32 字节。)

And here's the output:这是 output:

27

16776960

. .

Debugging:调试:

Instead of printing versionNumberAndPlaceNumber I also printed the whole if condition (indicating %d instead of %lu ) and got 0 as output thus the condition appears to be false.而不是打印versionNumberAndPlaceNumber我还打印了整个if条件(指示%d而不是%lu )并得到0作为 output 因此条件似乎是错误的。

But 16776960 = 0xFFFF00 and 0xFFFF00 AND 0xFF is 0 .但是16776960 = 0xFFFF000xFFFF00 AND 0xFF0

Why is 0 == 0 false ?为什么0 == 0 false

== operator has higher operator precedence, than & (bitwise AND) therefore your condition is equal to this ==运算符的运算符优先级高于& (按位与),因此您的条件等于此

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

Operator precedence describes the order in which operations will occur.运算符优先级描述了操作发生的顺序。 This is the same as PEMDAS in maths class and is to reduce the number of parentheses required.这与数学 class 中的 PEMDAS 相同,是为了减少所需的括号数量。 The == operator has a precedence of 9, & a precedence of 10, so the == operator grabs its arguments first. ==运算符的优先级为 9, &的优先级为 10,因此==运算符首先获取其 arguments。

This means that (a & b == c) is the same as (a & (b == c)) , which is not what you expected.这意味着(a & b == c)(a & (b == c))相同,这不是您所期望的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM