C++ Program to Convert Decimal Number to HexaDecimal Number

  • Write a C++ program to convert decimal to hexadecimal number.
  • Write a C++ program to convert hexadecimal to decimal number.

In this C++ programs we will learn about fundamentals of decimal and hexadecimal number system, how to convert decimal numbers to hexadecimal numbers and vice-versa. Given a decimal number we have to convert it to hexadecimal number.

Decimal number system is a base 10 number system using digits 0 and 9 whereas Hexadecimal number system is base 16 number system and using digits from 0 to 9 and A to F.
For Example:
2016 in Decimal is equivalent to 7E0 in Hexadecimal number system.

C++ program to convert decimal number to hexadecimal number

// C++ program to convert decimal numbers to hexadecimal numbers
#include <iostream>
#include <cstring>
using namespace std;
   
#define BASE_16 16
 
int main() {  
    char hexDigits[] = "0123456789ABCDEF"; 
   
    long decimal;  
    char hexadecimal[40];  
    int index, remaindar;  
       
    // Take a Decimal Number as input form user  
    cout << "Enter a Decimal Number\n";  
    cin >> decimal;   
   
    index = 0;
      
    // Convert Decimal Number to Hexadecimal Numbers 
    while(decimal != 0) { 
        remaindar = decimal % BASE_16;  
        hexadecimal[index] = hexDigits[remaindar];  
        decimal /= BASE_16;  
        index++;  
    }  
    hexadecimal[index] = '\0';  
   
    strrev(hexadecimal);  
   
    cout << "Hexadecimal Number : " << hexadecimal;  
   
    return 0;  
}
Output
Enter a Decimal Number
753
Hexadecimal Number : 2F1
Enter a Decimal Number
101
Hexadecimal Number : 3F2

In above program, we first declare a string hexDigits containing all digits of hexadecimal number system(0-9 and A-F). As hexadecimal numbers contains alphabets as digits, we have to use a character array to store hexadecimal numbers.


C++ program to convert hexadecimal number to decimal number

// C++ program to convert decimal numbers to hexadecimal numbers
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std; 
   
int main() {  
    long long decimalNumber=0;
    // Digits of hexadecimal number system. From 0 to 9 and from A to F
    char hexDigits[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
      '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    char hexadecimal[30];  
    int i, j, power=0, digit;  
   
    cout << "Enter a Hexadecimal Number\n";  
    cin >> hexadecimal;  
     
    // Converting hexadecimal number to decimal number
    for(i=strlen(hexadecimal)-1; i >= 0; i--) {
        // search currect character in hexDigits array
        for(j=0; j<16; j++){
            if(hexadecimal[i] == hexDigits[j]){
                decimalNumber += j*pow(16, power);
            }
        }
        power++;
    }  
  
    cout <<"Decimal Number : " << decimalNumber;  
   
    return 0;  
}
Output
Enter a Hexadecimal Number
2F1
Decimal Number : 753