Search code examples
cbitwise-operatorsbitwise-andbitwise-xorbitwise-or

Bitwise and doesn't work on unsigned long


I have this code where I use "bitwise and" (&) to try and change 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;

}

I compile and execute the code in order to get output:

x = 0
x = 0

But I expected:

x = 0
x = 1

Why?


Solution

  • It seems you mean the bitwise inclusive OR operator that can be used to set bits

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

    Or you could use another bitwise operator: the bitwise exclusive OR operator that can be used to toggle bits

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

    Otherwise 0 & 1 will give 0 because initially x was initialized by 0

    unsigned long x = 0;
    

    Here is a demonstration program

    #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 );
    }
    

    The program output is

    x = 0
    x = 1
    x = 1