Programming: Converting Decimal into Binary & Binary Into Decimal

Its been very important that you know all the techniques of converting a decimal into binary or vice-versa. Here I am going to show two techniques of converting a decimal into binary, one of them is using bit-manipulation and the other one is conventional.

One conventional method of converting decimal into binary is shown below:

Here is the implementation:

#include <iostream>

#include <math.h>

using namespace std;



void dec2bin(unsigned n, int a[])

/* This method is bit-manipulation */ 

{

   unsigned i, j=0;

   for(i = 1 << 15; i>0; i = i/2)

   {
a
  if(n & i)

  {

   a[j++] = 1;

  }

  else

  {

   a[j++] = 0;

  }

   }

}



void dec2bin2(int n)

/* Conventional Method */ 

{

   if(n>1)

  dec2bin2(n/2);

  

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

}



int main()

{

   int a[16] = {0}, i, sum=0;

   dec2bin(4, a);

   for(i=0; i<=15; i++)

  cout<<a[i];

   cout<<endl;

   //dec2bin2(65535);

   

   /* Below method will convert the binary into Decimal */
   for(i=0; i<16; i++)

   {

  sum+=((pow(2, (15-i)))*a[i]);

   }

   cout<<"Decimal: "<<sum;

   return 0;

}

I have shown two methods of converting the decimal number into binary and one method in the main() to show the conversion of binary in decimal number...

Let me know if you have any queries or above program requires any correction...
.... Next time... :)

0 comments:

Post a Comment

+