training

Code I wrote during training
git clone git://git.bitsmanent.org/training
Log | Files | Refs | README

numtab.c (1330B)


      1 /* Esercizio 4.25 */
      2 
      3 #include <stdio.h>
      4 #include <math.h>
      5 
      6 int main()
      7 {
      8    int num, c_num;
      9    int base; /* start from base 2 (binary) */
     10    int i, j, p;
     11 
     12    printf("Dec\tBin\tOct\tHex\n");
     13    for(num = 0; num <= 15; num++) {
     14       printf("%d\t", num);
     15 
     16       /* print equivalent in base "base" */
     17       /* base: 2, (4), 8, 16 */
     18       for(i = 1; i <= 4; i++) {
     19 
     20          /* dynamic base */
     21 	 if(i == 2) /* ignore base 4 */
     22 	    continue;
     23 	 base = pow(2, i);
     24 
     25          /* found the values order.. */
     26          for(j = 0; pow(base, j) <= num; j++) {
     27 	    p = pow(base, j);
     28          } /* ..and print the symbols one for one */
     29          c_num = num;
     30          for(j = p; j >= 1; j /= base) {
     31 	    if(base == 16 && c_num / j >= 10) {
     32 	    
     33 	       switch(c_num / j) {
     34 		  case 10:
     35 		     printf("A");
     36 		     break;
     37 		  case 11:
     38 		     printf("B");
     39 		     break;
     40 		  case 12:
     41 		     printf("C");
     42 		     break;
     43 		  case 13:
     44 		     printf("D");
     45 		     break;
     46 		  case 14:
     47 		     printf("E");
     48 		     break;
     49 		  case 15:
     50 		     printf("F");
     51 
     52 	       } /* end switch (c_num / j) */
     53 	       continue;
     54 	    } /* end if */
     55 
     56 	    printf("%d", c_num / j);
     57 	    if (!num) break;
     58 
     59 	    c_num %= j;
     60          } /* end for (j) */
     61 
     62 	 printf("\t");
     63 
     64       } /* end for (i) */
     65 
     66       printf("\n");
     67    } /* end for (num) */
     68 
     69    return 0;
     70 } /* E0F main */
     71