Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading