How to check each bit in 16 bit address in C

1k views Asked by At

I have a 16 bit address 0-15, I need to check at value of bit corresponding to their position in C

for example at 15 place i have 1, 14 has 0, and soo on!

|1|0|0|0|1|0|1|0|1|1|1|1|1|0|1|0|

I was thinking to create 16 new addresses with all zero and the position i am looking

2

There are 2 answers

0
Eugene Sh. On BEST ANSWER

Use a macro similar to this:

#define CHECK_BIT(x, i) ( ((x) & (1 << (i)) != 0 ) )

CHECK_BIT(x, i) will return true if the i'th bit of x is one, false otherwise.

1
David W On
int bitAtPosition(int value, int position){

   return (value & (1 << position)) != 0;
}