Wednesday, June 18, 2014

Binary Representation Of A Number using recursion

The code follows:

#include<stdio.h>

int convertIntoBinary(int n)
{
    if(n>1)
        convertIntoBinary(n/2);

    printf("%d",n%2);
}

int main()
{
    convertIntoBinary(50);
    return 0;
}


Viva La Raza
Sid

The Inspiration Of the above article has been taken from: geeksforgeeks.org

Binary Representation Of A Number

Hello my dear readers !.. Sorry for keeping you guyz  waiting for such a long time (i know i am being modest.. ;-) )..
Today's Post is all about Converting a number into its binary form.
The idea is derived from the fact that if we "AND (&) " a particular number with 1, that bit at unit's place will be extracted from the number. Similarly if we will shift 1 to it's left, the second last bit will be obtained and similarly so forth and so on. Hence the ith bit will be obained by doing AND operation of number and 1 at ith place.

The code of the program is as follows:

#include<stdio.h>

void convertIntoBinary(unsigned int n)
{
    unsigned int i=1;

    for(i=1<<31;i>0;i=i/2)
    {
        (n&i)?printf("1"):printf("0");
    }
}
int main()
{
    convertIntoBinary(50);
    return 0;
}

Any questions as well as suggestions are always welcome.
Do comment if you like the article.

Viva La Raza
Sid


The Inspiration Of the above article has been taken from: geeksforgeeks.org