1

Why does it print that bit number 6 of 47(00101111) is 1.Counting the bits starts from the right side starting with 1?

 #include <stdio.h>
    #include <stdlib.h>

    int main()
    {
        int mask1,mask2;

        //bit  testing;
        mask1=1<<3;
        mask2=1<<6;
        if(47&mask1!=0)
            printf("\n bit number 3 is 1");
        else
            printf("\n bit number 3 is 0");
        if(47&mask2!=0)
            printf("\n bit number 6 is 1");
        else
             printf("\n bit number 6 is 0");

        return 0;
    }
Michael
  • 82
  • 5

1 Answers1

7

The bitwise AND operator & has lower precedence than the inequality operator !=. So this:

47&mask1!=0

Is the same as:

47&(mask1!=0)

Add parenthesis as follows:

(47&mask1)!=0

And you'll get the expected results. Be sure to do the same for the check against mask2.

dbush
  • 205,898
  • 23
  • 218
  • 273