C++ Program to Convert Decimal to Hexadecimal

C++ program to convert decimal to hexadecimal is provided on this page.

A decimal number is most commonly used number in number system, we use it everyday in our lives.

Decimal number is made of whole or integer part and non-integer part or fractional part.

For example, consider the number 17.591. In this number, 17 is whole number part and 0.591 is fractional or non-integer part.

A decimal number system is also known as base 10 system because it contains 10 numbers 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.

That was easy. Now to hexadecimal number.

Hexadecimal number is a numbering system that is also known as base 16 which means it contains 16 numbers or units.

The 16 units are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15.

The numbers from 10 to 15 are represented by alphabets A-F or a-f.

C++ program to convert decimal to hexadecimal

Here is the c++ program which converts a decimal number into its equivalent hexadecimal part.

#include<iostream> 
using namespace std;
  
void decimal_to_hexadecimal(int number) 
{    
    char hexadecimal_number[100]; 
    
    int i = 0; 
    
    while(number != 0)
    {    
        int temp  = 0; 
        
        temp = number % 16; 
          
        if(temp < 10) 
        { 
            hexadecimal_number[i] = temp + 48; 
            i++; 
        } 
        else
        { 
            hexadecimal_number[i] = temp + 55; 
            i++; 
        } 
          
        number = number/16; 
    } 
      
      cout << "Hexadecimal number :";
    for(int j=i-1; j>=0; j--) 
        cout <<hexadecimal_number; 
}


int main() 
{ 
    int number = 1111; 
      
    decimal_to_hexadecimal(number); 
      
    return 0; 
} 

Output:

Hexadecimal number : 457

Comments