You can printf an integer in many forms, including decimal, octal or hexadecimal. What about binary? This is not the first time someone asks me this, so I’ll just post it here:

>  ./dec2bin 3
3 -> 00000000000000000000000000000011
>  ./dec2bin 4
4 -> 00000000000000000000000000000100
>  ./dec2bin 5
5 -> 00000000000000000000000000000101
>  ./dec2bin 6
6 -> 00000000000000000000000000000110
>  ./dec2bin 7
7 -> 00000000000000000000000000000111

A simple solution could be the function below, note that it is limited to 32 bits:

static char *dec2bin(int dec)
{
        char *str, *ret;
        int i;
        const int bits = 32;
 
        ret = str = malloc(bits);
        memset(str, '0', bits);
 
        for (i = bits-1; i >= 0; i--) {
                if (dec % 2 == 1)
                        str[i] = '1';
 
                dec /= 2;
        }
 
        str[bits] = '\0';
 
        return ret;
}

If you enjoyed this post, make sure you subscribe to my RSS feed!