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:

 

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++

Comments

  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;
    }

    • 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.

  2. It works great… but its valid only upto 13 characters, what if i want to give around 30 35 characters for input…

    kindly help me out for this.

  3. Take the data types of varaibles as long double that will provide the maximum number possible, I don’t think anybody wants convert 30-35 characters input in c++