Geeksforgeeks: Android App Geeksquiz
Geeksforgeeks: Android App Geeksquiz
GeeksforGeeks
A computer science portal for geeks
Home
Algorithms
DS
GATE
Interview Corner
Q&A
C
C++
Java
Books
Contribute
Ask a Q
About
Array
Bit Magic
C/C++
Articles
GFacts
Linked List
MCQ
Misc
Output
String
Tree
Graph
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
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.
void bin(unsigned n)
{
unsigned i;
for (i = 1 << 31; i > 0; i = i / 2)
(n & i)? printf("1"): printf("0");
}
int main(void)
{
bin(7);
printf("\n");
bin(4);
}
Method 2: Recursive
Following is recursive method to print binary representation of ‘NUM’.
void bin(unsigned n)
{
/* step 1 */
if (n > 1)
bin(n/2);
/* step 2 */
printf("%d", n % 2);
}
int main(void)
{
bin(7);
printf("\n");
bin(4);
}
Related Topics:
Like 7 Tweet 2 1
Writing code in comment? Please use ideone.com and share the link here.
int main()
int n,i,j;
int a[100]={0};
scanf("%d",&n);
i =0;
while(n>0)
a[i]=n%2;
see more
• Reply • Share ›
int bin(int x) {
GeeksforGeeks
Like
Interview Experiences
Advanced Data Structures
Dynamic Programming
Greedy Algorithms
Backtracking
Pattern Searching
Divide & Conquer
Mathematical Algorithms
Recursion
Geometric Algorithms
Popular Posts
All permutations of a given string
Memory Layout of C Programs
Understanding “extern” keyword in C
Median of two sorted arrays
Tree traversal without recursion and without stack!
Structure Member Alignment, Padding and Data Packing
Intersection point of two Linked Lists
Lowest Common Ancestor in a BST.
Check if a binary tree is BST or not
Sorted Linked List to Balanced BST
Recent Comments
Ashish Jaiswal
Given a binary tree, print out all of its root-to-leaf paths one per
line. · 31 minutes ago
anuj
Sahil Mutneja
chetan
chetan
Guest
Search in a row wise and column wise sorted matrix · 3 hours ago