Program to convert Decimal to Hexadecimal C++

Decimal Number System: 

It is base 10 number system which uses the digits from 0 to 9.

Hexadecimal Number System:

It is base 16 number system which uses the digits from 0 to 9 and A, B, C, D, E, F.

Logic to Convert Decimal to Hexadecimal C++:

  1. Divide the original decimal number by 16.
  2. Divide the quotient by 16.
  3. Repeat the step 2 until we get quotient equal to zero.
  4. Equivalent Hexadecimal number would be the remainders of each step in the reverse order.

Download Source Code:

 

[adinserter block=”1″]

Download: dectohex.cpp

PROGRAM:

#include<iostream>
using namespace std;

int main()
{
    long int decimalNumber,remainder,quotient;
    int i=1,j,temp;
    char hexadecimalNumber[100];

    cout<<"Enter any decimal number: ";
    cin>>decimalNumber;

    quotient = decimalNumber;

    while(quotient!=0)
    {
         temp = quotient % 16;

      //To convert integer into character
      if( temp < 10)
           temp =temp + 48;
      else
         temp = temp + 55;

      hexadecimalNumber[i++]= temp;
      quotient = quotient / 16;
    }
    cout<<"nEquivalent hexadecimal number of "<<decimalNumber<<" is : ";
    for(j = i -1 ;j> 0;j--)
      cout<<hexadecimalNumber[j];
    cout<<endl;
    return 0;
}

 

How Code Works:

Let user enter 900.

  • 900 / 16  Remainder : 4 , Quotient : 56
  •  56 / 16  Remainder : 8 , Quotient : 3
  •  3 / 16  Remainder : 3 , Quotient : 0

Now Hexadecimal Number is remainders in each step in reverse order i.e. 384

Hence, hexadecimal equivalent of 900 is 384.

OUTPUT:

decimal to hexadecimal C++

2 thoughts on “Program to convert Decimal to Hexadecimal C++

  1. can you explain this part of the code?

    while(quotient!=0)
    {
    temp = quotient % 16;

    //To convert integer into character
    if( temp < 10)
    temp =temp + 48;
    else
    temp = temp + 55;

    hexadecimalNumber[i++]= temp;
    quotient = quotient / 16;
    }

    1. In ASCII there is a gap in the table between numbers 0-9 and the letters A-Z. The decimal number is being changed to char, however the ASCII decimal value of 0 is equal to [NULL]. By adding 48 when the entry is less than 10, < 10, you get the char value for the decimal entry. EX| if your entry is 3, 3+48 gives you the ASCII char value for the number 3. When the decimal number is greater than 10, in hexadecimal the value is a letter A-F. The conversion of temp + 55 simply assigns the char value of the corresponding number. EX| 10 = A in hex so, 10 + 55 gives the char value A. This is all because of conversions from integers to char relate to the ASCII table. My suggestion is that you find a table and go through the code, converting integer to char and so on, this should help you understand that conversion.

Leave a Reply