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

Source: Microsoft Interview Set-3

Method 1: Iterative
For any number, we can check whether its ‘i’th bit is 0(OFF) or 1(ON) by bitwise  ANDing it with “2^i” (2 raise to i).

1) Let us take number 'NUM' and we want to check whether it's 0th bit is ON or OFF	
	bit = 2 ^ 0 (0th bit)
	if  NUM & bit == 1 means 0th bit is ON else 0th bit is OFF

2) Similarly if we want to check whether 5th bit is ON or OFF	
	bit = 2 ^ 5 (5th bit)
	if NUM & bit == 1 means its 5th bit is ON else 5th bit is OFF.

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.

[ad type=”banner”] [pastacode lang=”c” manual=”void%20bin(unsigned%20n)%0A%7B%0A%20%20%20%20unsigned%20i%3B%0A%20%20%20%20for%20(i%20%3D%201%20%3C%3C%2031%3B%20i%20%3E%200%3B%20i%20%3D%20i%20%2F%202)%0A%20%20%20%20%20%20%20%20(n%20%26%20i)%3F%20printf(%221%22)%3A%20printf(%220%22)%3B%0A%7D%0A%20%0Aint%20main(void)%0A%7B%0A%20%20%20%20bin(7)%3B%0A%20%20%20%20printf(%22%5Cn%22)%3B%0A%20%20%20%20bin(4)%3B%0A%7D” message=”C Programming” highlight=”” provider=”manual”/]

Method 2: Recursive
Following is recursive method to print binary representation of ‘NUM’.

step 1) if NUM > 1
	a) push NUM on stack
	b) recursively call function with 'NUM / 2'
step 2)
	a) pop NUM from stack, divide it by 2 and print it's remainder.
[pastacode lang=”c” manual=”void%20bin(unsigned%20n)%0A%7B%0A%20%20%20%20%2F*%20step%201%20*%2F%0A%20%20%20%20if%20(n%20%3E%201)%0A%20%20%20%20%20%20%20%20bin(n%2F2)%3B%0A%20%0A%20%20%20%20%2F*%20step%202%20*%2F%0A%20%20%20%20printf(%22%25d%22%2C%20n%20%25%202)%3B%0A%7D%0A%20%0Aint%20main(void)%0A%7B%0A%20%20%20%20bin(7)%3B%0A%20%20%20%20printf(%22%5Cn%22)%3B%0A%20%20%20%20bin(4)%3B%0A%7D” message=”C Programming” highlight=”” provider=”manual”/] [ad type=”banner”]