9511_workbook

solved exercises from algorithms & programming I (9511) prof. Cardozo
Index Commits Files Refs README
guia03/ex25_imp.c (1082B)
   1 //    Reads an integer from stdin and prints it
   2 //    on stdout in binary base.
   3 //    only for numbers below 128; 
   4 
   5 #include <stdio.h>
   6 #include <stdlib.h>
   7 
   8 #define MAX_LEN    8 
   9 #define ERR_MSG_NEG "Err: invalid number!"
  10 
  11 int main ( void ) {
  12 
  13     int i, num;
  14     char buffer[MAX_LEN];
  15 //    0000 0000
  16     int bin[MAX_LEN] = {0,0,0,0,0,0,0,0};
  17 
  18     if(fgets(buffer, MAX_LEN, stdin) == NULL)
  19         return 1;
  20 
  21 //    Converts the input str to int, if the number
  22 //    is negative or greater than 128, puts an 
  23 //    error message on stderr;
  24     if((num = atoi(buffer)) < 0 || num > 128) {
  25         fprintf(stderr, ERR_MSG_NEG"\n");
  26         return 1;
  27     }
  28 
  29 //    Converts num to binary base by dividing it
  30 //    by 2 until its zero, the rest of the division
  31 //    is stored in every itineration in bin[];
  32     for(i = 0; num != 0; i++) {
  33         if((num % 2) == 1) {
  34             bin[i] = 1;
  35         } else {
  36             bin[i] = 0;
  37         }
  38         num = (num / 2);
  39     }
  40 
  41 //    This part print bin in reverse order because
  42 //    the previous algorithm stores the values in 
  43 //    reverse order;
  44     for(i = 7; i >= 0; i--) {
  45         if(i == 3)
  46             putchar(' ');
  47 
  48         printf("%d", bin[i]);
  49     }
  50 
  51     putchar('\n');
  52     return 0;
  53 }