Convert decimal to binary in C

This is an example C program for converting decimal to binary.

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

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;
}

(download)

The output of the example looks like this:

Decimal 1 = binary 1
Decimal 2 = binary 10
Decimal 6 = binary 110
Decimal 7 = binary 111
Decimal 1000 = binary 1111101000


Copyright © Ben Bullock 2009-2018. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer