I have written one small program to check whether particular bit is set or not. But not getting proper value when i check for upper nibble.

#define check(var,pos) ((var)&(1<<pos))
void main()

int var=30;// in binary 0011 0000 that is its 4th and 5th bits are set;
int bit;
printf("enter position where we want to check whether bit is set or not ");


output: when entered position 4th (1<<4 =0001 0000) , bit value is 16 and when entered position is 5th(1<<5=0010 0000), bit value is 0.
please let me know why it is so?I get the proper bit value when lower nibbles of var are set.

// in binary 0011 0000 that is its 4th and 5th bits are set;

Incorrect. 30 in binary is 00011110.

Type in 4 and you get 1 << 4, which is 16 in decimal.

00000001 shift left 4 ---> 00010000.

When you AND 00010000 & 00011110, you get 00010000, or 16, which is what prints out. Since 30 has the 4th bit set (where the LSB is bit 0), the program functions exactly as you wrote it.

When you type in 5 and shift 1 five places, you get 32, which is more than 30, so bit 5 is NOT set for 30. Hence you again get 0. The problem is you made a mistake when converting 30 to binary. Either that or you meant 0x30, not 30. If you wanted to convert 0x30 to binary, that WOULD be 00110000. However, you specify hexadecimal nowhere. If you want hexadecimal, change line 5 to the following...

int var = 0x30; // 0x denotes hexadecimal.

Thanks for your reply.You are right.I should have specified it as 0x30 for binary 00110000
My mistake. i tried it again by changing line 5 as you suggested and its working fine now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.