按位且不适用于 unsigned long

Bitwise and doesn't work on unsigned long

我有这段代码,我使用 "按位和" (&) 尝试更改 x:

#include <stdio.h>

int main (void){

    unsigned long x = 0;
    printf("x = %lu\n", x);

    x &= 1;
    printf("x = %lu\n", x);

    return 0;

}

我编译并执行代码以获得输出:

x = 0
x = 0

但我预计:

x = 0
x = 1

为什么?

您的意思似乎是可以用于设置位的按位包含或运算符

x |= 1;
printf("x = %lu\n", x);

或者您可以使用另一个按位运算符:可用于切换位的按位异或运算符

x ^= 1;
printf("x = %lu\n", x);

否则0 & 1会给出0因为最初x是由0

初始化的
unsigned long x = 0;

这是一个演示程序

#include <stdio.h>

int main( void )
{
    unsigned long x = 0;
    printf( "x = %lu\n", x );

    x |= 1;
    printf( "x = %lu\n", x );

    x = 0;
    x ^= 1;
    printf( "x = %lu\n", x );
}

程序输出为

x = 0
x = 1
x = 1