C - Write program to output value in binary, hexadecimal, and decimal form

Requirements

Write program to output value in binary, hexadecimal, and decimal form

Demo

#include <stdio.h>

char *to_binary(int n);

int main()/*from w  ww .  j a v a 2s  . c  o  m*/
{
    int b,x;

    b = 21;

    for(x=0;x<8;x++)
    {
        printf("%s 0x%04X %4d\n",to_binary(b),b,b);
        b<<=1;
    }

    return(0);
}

char *to_binary(int n)
{
    static char bin[17];
    int x;

    for(x=0;x<16;x++)
    {
        bin[x] = n & 0x8000 ? '1' : '0';
        n <<= 1;
    }
    bin[x] = '\0';
    return(bin);
}

Result

Related Exercise