Tuesday, October 26, 2010

Bit and boolean fundamentals

Teaching my brother :-)

Decimal to binary

#include <stdio.h>



int main (int argc, char *argv[])
{
 unsigned long number_to_test = 42; 
 unsigned long mask;  
 
 
 printf("\nFirst: ");
 for (mask = 1 << 31; mask != 0; mask >>= 1) 
  printf("%d " , (number_to_test & mask));
  
 printf("\nSecond: ");
 for (mask = 1 << 31; mask != 0; mask >>= 1) 
  printf("%d", !(number_to_test & mask));

 
 printf("\nThird: "); 
 for (mask = 1 << 31; mask != 0; mask >>= 1) 
 {  
  putchar('0' + !!(number_to_test & mask));
  // printf("%d", !!(number_to_test & mask));
 }
 
 printf("\nFourth: ");
 for (mask = 1 << 31; mask != 0; mask >>= 1) 
 {
  if (number_to_test & mask)  
   putchar('1');
  else
   putchar('0');
 }

     
 printf("\nFifth: "); 
 for (mask = 1 << 31; mask != 0; mask >>= 1) 
  putchar( (number_to_test & mask) ? 'Y' : 'N' );
          

    
     
 puts("\n\nTesting boolean logic not");  
 
 printf("\n%d", ! 4);
 
 printf("\n%d", ! 7);
 
 printf("\n%d", ! 0);

 
 puts("\n\nTesting boolean logic not not");  
 
 printf("\n%d", ! ! 4);
 
 printf("\n%d", ! ! 7);
 
 printf("\n%d", ! ! 0);
 
  
 return 0;
}



Output
First: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32 0 8 0 2 0 
Second: 11111111111111111111111111010101
Third: 00000000000000000000000000101010
Fourth: 00000000000000000000000000101010
Fifth: NNNNNNNNNNNNNNNNNNNNNNNNNNYNYNYN

Testing boolean logic not

0
0
1

Testing boolean logic not not

1
1
0

No comments:

Post a Comment