Integer to Binary Representation (C/C++)

/*
** filename: hextobin.c
**/

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

/* Example input/output
** hexnum = 41, binstr = "101001"
**/
void hextobin (unsigned int hexnum, char *binstr) {
    char tstr[128];
    int i,j;

    if ( (hexnum == 0) || (hexnum == 1) ) {
        binstr[0] = hexnum ? '1' : '0';
        binstr[1] = '\0';
        return;
    }

    /* simple conversion steps, except the bits are inserted
    ** in the string in reverse order
    **/
    i=0;
    while (hexnum > 1) {
        tstr[i++] = (hexnum % 2) ? '1' : '0';
        hexnum /= 2;
    }
    tstr[i] = '1';

    /* reverse the string, to correct the bit order */
    j=0;
    while ( i >= 0) {
        binstr[j++] = tstr[i--];
    }
    binstr[j] = '\0';
}

/* Compile
**   gcc -o hextobin hextobin.c
** test
** ./hextobin 41
** input=41, hex=0x29, binary=101001
** ./hextobin 0x22
** input=34, hex=0x22, binary=100010
**/
int main(int argc, char *argv[]) {
    unsigned int ival;
    char binstr[128];

    if (argc <= 1) {
        printf ("Usage: %s <number>\n", argv[0]);
        printf ("    where <number> can be in decimal or hex (prefix with 0x)\n");
        return -1;
    }
    ival = strtoul (argv[1], NULL, 0);
    hextobin (ival, binstr);
    printf ("input=%u, hex=0x%x, binary=%s\n", ival, ival, binstr);
    return (0);
}

Leave a Reply