Bit position: 6543210
Starting bit pattern: ..............x...............
Bit mask: 000000000000001000000000000000
----------------------------------------- AND
00000000000000x000000000000000
The result is equal to 0 (000000000000000000000000000000) if bit x is 0
The result is not equal to 0 if bit x is 1
|
i positions
<-------------->
1 << i = 000000..1000000000000000
|
int x;
int i;
if ( (x & (1 << i )) != 0 )
{
bit at position i is ONE;
}
else
{
bit at position i is ZERO;
}
|
#define ISSET( x, i ) (( x & (1 << i)) != 0 ) |
The following printBits( ) C function will print an int variable (parameter) out in binary:
#include <stdio.h>
void printBits(int x)
{
for (int i = 31; i >= 0; i--)
{
if ( x & (1 << i) /* i-th bit in x is 1 */ )
printf("1");
else
printf("0");
}
}
int main( int argc, char* argv[] )
{
int a = 7;
printf("a = %d, in binary: ", a);
printBits(a);
printf("\n\n");
}
|
How to run the program:
|