I asked this question in an interview. Suppose 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 feel that this is not what they were looking for.
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 there a ^ 0x4will be less arithmetic value, then a.
0x4
a ^ 0x4
a
if((a | (1<<2)) ^ a) printf("3rd bit is not set"); else printf("3rd bit is set");
as requested only with XOR. bit 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; }