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.
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.
Method 3: Recursive using bitwise operator
Steps to convert decimal number to its binary representation are given below:
step 1: Check n > 0 step 2: Right shift the number by 1 bit and recursive function call step 3: Print the bits of number
This article is compiled by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Convert decimal fraction to binary number
- Check if binary representation of a number is palindrome
- Bitwise Operators in C/C++
- How to swap two numbers without using a temporary variable?
- Find position of the only set bit
- Swap all odd and even bits
- Write your own strcmp that ignores cases
- Find the element that appears once
- Count total set bits in all numbers from 1 to n
- Rotate bits of a number
- Count number of bits to be flipped to convert A to B
- Count set bits in an integer
- Write an Efficient C Program to Reverse Bits of a Number
- Position of rightmost set bit
- Program to find whether a no is power of two