Wednesday, 1 April 2015

Convert the Decimal value to the binary in C++

Convert the Decimal value to the binary in Cpp with code example:

We can convert the decimal values to binary values in two different ways
In this example one we need to include the iomanip to convert decimal to binary
#include <iomanip> 


Example 1:
#include "stdafx.h" 
#include <iostream>
using namespace std;
#include <iomanip>
void ConvertDec2Binary(unsigned int uiVal)
{
  int i2Upper;

  if(uiVal < 256)

  i2Upper = 128;

  else

  i2Upper = 32768;

cout << setw(5) << uiVal << ": ";

// check if bit is set starting from the highest bit

// (ex) i2Upper = 128, 10000000, 01000000, 00100000, ..., 00000001

for(int iIndex = i2Upper; iIndex > 0; iIndex = iIndex/2) {

  if(uiVal & iIndex) cout << "1 "; else cout << "0 ";

}

cout << "\n"; }

int main ()

{
  ConvertDec2Binary(10);

  ConvertDec2Binary(100);

  ConvertDec2Binary(1000);

  ConvertDec2Binary(10000);

  ConvertDec2Binary(100000);

  getchar ();

  return 0;

}

The output of the above program is
   10: 0 0 0 0 1 0 1 0

  100: 0 1 1 0 0 1 0 0

 1000: 0 0 0 0 0 0 1 1 1 1 1 0 1 0 0 0

10000: 0 0 1 0 0 1 1 1 0 0 0 1 0 0 0 0

100000: 1 0 0 0 0 1 1 0 1 0 1 0 0 0 0 0


Example 2:
In this example one we need to include the bitset to convert decimal to binary
#include <bitset>
#include "stdafx.h"

#include <iostream>
using namespace std;
#include <bitset>
void ConvertDec2Binary(unsigned int uiVal)
{
  cout << setw (15) << uiVal << ": ";
  cout << bitset <12>((int)uiVal);
  cout << "\n";
}
int main()
{
  ConvertDec2Binary(10);
  ConvertDec2Binary(100);
  ConvertDec2Binary(1000);
  ConvertDec2Binary(10000);
  ConvertDec2Binary(100000);
  getchar ();
  return 0;
}

The output of the above program is:
             10: 000000001010

            100: 000001100100

           1000: 001111101000

          10000: 011100010000

         100000: 011010100000


Example:3
#include "stdafx.h"
#include <iostream>
using namespace std;
void ConvertDec2Binary(int iVal)
{
  char szVal[100]; int iIndex = 0;
   while(iVal > 0) {
     if(iVal % 2 == 0 ) szVal[iIndex++] = '1';
     else szVal[iIndex++] = '0'; iVal = iVal /2;
   }
   szVal[iIndex] = '\0';
   cout << szVal << endl;
}
int main()
{
  ConvertDec2Binary(10);
  ConvertDec2Binary(100);
  ConvertDec2Binary(1000);
  ConvertDec2Binary(10000);
  ConvertDec2Binary(100000);
  getchar ();
  return 0;
}

The above example using simple mathematical equations to convert decimal values to the binary values
The output of the above program is:
1010

1101100

1110100000

11110111000110

11111010100111100



No comments: