Stoica Dan
Stoica Dan

Reputation: 81

In C, how can you check if a bit is set using XOR?

I got this question asked at in interview. Supposing I have to check bit 3 for:

 a=0x9004;

I said that

 if((a<<13>>15)^1==1)
     printf("bit 3 is not set");
 else
     printf("bit 3 is set");

But I'm feeling that this is not what they were looking for.

Upvotes: 3

Views: 604

Answers (3)

tesseract
tesseract

Reputation: 901

as requested only Using XOR. bit count starts from 0 to bit 31.

#include <stdio.h>
//assuming you count from bit 0, bit 1,bit 2 up to bit 31..
int main(void){

int a = 0x7FFFFFFF;
int check = (1<<3);
check = (a - (check^a) )>0 ? 1:0;
printf("bit 3 of %x is set to %d",a,check);
return 0;
}

Upvotes: 2

Prince John Wesley
Prince John Wesley

Reputation: 63698

if((a | (1<<2)) ^ a)
   printf("3rd bit is not set");
else printf("3rd bit is set");

Upvotes: 5

Sergey L.
Sergey L.

Reputation: 22542

if ((unsigned int )a ^ (0x4) < (unsigned int )a) 
    printf("bit 3 is set");
else
    printf("bit 3 is not set");

If bit 3 (0x4) was set then a ^ 0x4 will be smaller arithmetic value then a.

Upvotes: 5

Related Questions