C - Write program to display 16 bits int value in binary

Requirements

Write program to display 16 bits int value in binary

Hint

The max value of 16 bits of integer is 65535.

Demo

#include <stdio.h>

char *to_binary(int n);

int main()/*from w  w  w  .j  a  v  a  2s .  c o  m*/
{
    int input;

    printf("Type a value 0 to 65535: ");
    scanf("%d",&input);
    printf("%d is binary %s\n",input,to_binary(input));
    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