C - Displaying binary values

Introduction

The following code presents a binary output function called to_binary().

The to_binary() function converts an int value to a string representing that int value in binary digits.

Demo

#include <stdio.h> 

char *to_binary(int n); 

int main() //from ww w  . ja v a2  s. c  o m
{ 
    int input; 

    printf("Type a value 0 to 255: "); 
    scanf("%d",&input); 
    printf("%d is binary %s\n",input,to_binary(input)); 
    return(0); 
} 

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

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

Result

Related Topic