#include #include #include static void decimal_to_binary (int number) { char * digits; int n_digits; int i; int copy; /* Count how many digits are necessary. */ copy = number; n_digits = 0; while (copy) { n_digits++; copy /= 2; } /* Get space for the digits. */ digits = malloc (n_digits); if (! digits) { fprintf (stderr, "No more memory.\n"); exit (EXIT_FAILURE); } /* Fill the digits from the number. */ i = 0; copy = number; while (copy) { digits[i] = copy % 2; copy /= 2; i++; } /* Output stage. */ printf ("Decimal %d = binary ", number); for (i = n_digits - 1; i >= 0; i--) { printf ("%d", digits[i]); } printf ("\n"); free (digits); } int main (int argc, char ** argv) { int i; const int base = 10; for (i = 1; i < argc; i++) { /* Convert each argument to a string. */ char * arg; char * end; int number; arg = argv[i]; number = strtol (arg, & end, base); if (arg != end) { decimal_to_binary (number); } } return 0; }