|
We have used a shift operation to construct the pattern 000..00100..000 before !!
|
|
Note: C programmers often define ISSET as a macro: #define ISSET(x,k) ((x & (1 << k)) != 0)
ISSET(x,k) can be used to print a variable out in binary by testing each individual bit in the variable:
#include <stdio.h>
void printBits(int x) // Function declaration
#define ISSET(x,k) ((x & (1 << k)) != 0)
int main( int argc, char* argv[] )
{
int a = 7;
printf("a = %d, in binary: ", a);
printBits(a);
printf("\n\n");
}
void printBits(int x)
{
for (int i = 31; i >= 0; i--)
{ Print x out in binary
if ( x & (1 << i) /* i-th bit in x is 1 */ )
printf("1");
else
printf("0");
}
}
|
ISSET(x,k) can be used to print a variable out in binary by testing each individual bit in the variable:
#include <stdio.h> void printBits(int x) // Function declaration #define ISSET(x,k) ((x & (1 << k)) != 0) int main( int argc, char* argv[] ) { int a = 7; printf("a = %d, in binary: ", a); printBits(a); printf("\n\n"); } void printBits(int x) { for (int k = 31; k >= 0; k--) // Go through all 32 bits in x { if ( x & (1 << i) /* i-th bit in x is 1 */ ) printf("1"); else printf("0"); } } |
ISSET(x,k) can be used to print a variable out in binary by testing each individual bit in the variable:
#include <stdio.h> void printBits(int x) // Function declaration #define ISSET(x,k) ((x & (1 << k)) != 0) int main( int argc, char* argv[] ) { int a = 7; printf("a = %d, in binary: ", a); printBits(a); printf("\n\n"); } void printBits(int x) { for (int k = 31; k >= 0; k--) // Go through all 32 bits in x { if ( ISSET(x,k) ) printf("1"); // Bit k is 1 ==> print "1" else printf("0"); // Bit k is 0 ==> print "0" } } |
DEMO: demo/C/set1/print-binary.c