【发布时间】:2020-04-06 09:56:07
【问题描述】:
versionNumberAndPlaceNumber是0xFFFF00下面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 = 0xFFFF00 和0xFFFF00 AND 0xFF 是0。
为什么是0 == 0 false?
【问题讨论】:
-
条件
(a & b == c)与(a & (b == c))相同。 -
对,当我查看 C 运算符优先级时,我看了一眼,将“&”地址运算符与“&”位运算符混为一谈。地址运算符的优先级高于
==,但按位运算符没有。 -
如果对复杂表达式有疑问,请使用方括号,否则使用方括号。
标签: c if-statement bitwise-operators endianness unsigned-long-long-int