Sunday, March 16, 2014

Decimal to Hexadecimal converter (basic way)


Here is a basic way to get  the hexadecimal value of a decimal number. In this program, a for loop is used which will get the remainder, decrease the number by dividing it by 16 and populate the array. At the end, we will simply print the array in reverse order. For remainder values greater than 9, a function is present which gives alphabetic values of numbers 10-15.                                                                                                                                                             

#include<iostream.h>

#include<conio.h>

void hex(int [], int);

void main()

{

int num,rem,div,i=0,a[100];

cout<<"Enter the number :  ";

cin>>num;                                      //getting the number

for (div=num/16;div>0;)

{

if (i==0)

rem=num%16;

else                                   //dividing number by 16 to get remainder and next number

{

rem=div%16;

div=div/16;

}

a[i]=rem;                             //populating array with the remainder

i++;

}

cout<<endl<<"The Hexadecimal Value of given number is :  ";

for (int k=i-1;k>=0;k--)

{

if (a[k]>9)

hex(a,k);                              //if remainder > 9

else

cout<<a[k];                           //printing array

}

getch();

}

 void hex(int a[], int k)

 {

 if (a[k]==10)

 cout<<'A';

  else if (a[k]==11)

  cout<<'B';

   else if (a[k]==12)

  cout<<'C';

    else if (a[k]==13)                  //Values of remainder > 9

  cout<<'D';

     else if (a[k]==14)

  cout<<'E';

      else if (a[k]==15)

  cout<<'F';

  }


Widgets

 

Copyright @ 2014 CPP Fuzz.