Spread the love

Write a program to print Binary representation of a given number.

 

/* Binary representation of number */

#include<stdio.h>

void bin(unsigned n)
{
    unsigned i;
    for (i = (1 << 31) ; i > 0; i = (i>>1))
        if(n & i)
			printf("1");
		else
			printf("0");
}
 
int main(void)
{
    bin(7);
}

 

Code Explanation

for loop is little bit complex here so lets explain it first 

  • i is initialize with 1000 0000 0000 0000, we mention it (1<<31) which left shift the 1, 31 times.
  • Then we right shift i by 1 after every iteration on operation column of for loop .

Logic of Code :- Let us take unsigned integer (32 bit), which consist of 0-31 bits. To print binary representation of unsigned integer, start from 31th bit, check whether 31th bit is ON or OFF, if it is ON print “1” else print “0”. Now check whether 30th bit is ON or OFF, if it is ON print “1” else print “0”, do this for all bits from 31 to 0, finally we will get binary representation of number.

Suggested Reading

  1. Convert decimal number into hexadecimal octal binary – single universal logic
  2. Write a c Program to convert decimal to Hexadecimal number