• C

# Macro definition to write a program to test a bit.

how do you write a macro to test whether a bit in a byte is set or not set?

For example if we want to test the fourth bit of a byte, how do we do it using the macro.

###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
Hi suresh204,

#define ISSET4(X) (X)&(0x8)

Cheers!
Sunny:o)
Commented:
a small explanation is in order ...

given any byte say
1 1 0 1   1 0 1 0
to determine if nth bit is 1, bitwise AND it with a number which has all bits except nth bit as 0 ... here to determine, 4th bit we use
0 0 0 0   1 0 0 0

1 1 0 1   1 0 1 0
&   0 0 0 0   1 0 0 0
----------------------------------------------------
0 0 0 0    1 0 0 0
since answer is non zero, fourth bit is set

this is also referred to as masking .. since in the constant used, all other bits are set to 0 and 0 anded with anything gives a zero, the result depends on the only set bit in the constant (mask)
Commented:
You can use the following macro also:
#define IS_BIT_SET(X, pos) (0x01 << (pos - 1)) & (X)

"pos" is the bit which you want to test for number "X". Count starts from right. So rightmost bit is 1, next is 2, etc.

Experts Exchange Solution brought to you by