C++ Program For Hexadecimal To Decimal Conversion

Last Updated : 25 Aug, 2026

A hexadecimal number uses base 16 and the digits 0–9 and A–F, where A–F represent values from 10–15. To convert it into decimal, each digit is multiplied by its corresponding power of 16.

  • Traverse the hexadecimal number from right to left.
  • Multiply each digit by the corresponding power of 16 and add the values to get the decimal equivalent.

Examples:

Input: hex = "1A"
Output: 26

Input: hex = "1AB"
Output: 427

hexadecimal to decimal conversion in C++

Approach

  • Initialize decValue as 0 and base as 1 (16^0).
  • Traverse the hexadecimal string from right to left.
  • Convert each character into its corresponding decimal value.
  • Multiply the digit value by the current base and add it to decValue.
  • Multiply base by 16 for the next position.
  • Return decValue as the decimal equivalent.
C++
#include <iostream>
#include <string>
using namespace std;

// Function to convert hexadecimal to decimal
int hexadecimalToDecimal(const string& hexVal)
{
    int decValue = 0;
    int base = 1; // Represents 16^0

    // Traverse the hexadecimal string from right to left
    for (int i = hexVal.length() - 1; i >= 0; i--) {

        int digit;

        // Convert characters '0'-'9' to values 0-9
        if (hexVal[i] >= '0' && hexVal[i] <= '9') {
            digit = hexVal[i] - '0';
        }

        // Convert characters 'A'-'F' to values 10-15
        else if (hexVal[i] >= 'A' && hexVal[i] <= 'F') {
            digit = hexVal[i] - 'A' + 10;
        }

        // Ignore invalid hexadecimal characters
        else {
            continue;
        }

        // Add digit × corresponding power of 16
        decValue += digit * base;

        // Move to the next power of 16
        base *= 16;
    }

    return decValue;
}

int main()
{
    string hexNum = "1A";

    cout << hexadecimalToDecimal(hexNum);

    return 0;
}

Output
26

Explanation: For hexNum = "1A":

  • The last digit A represents 10, and its place value is 16⁰ = 1.
  • The digit 1 has place value 16¹ = 16.
  • Therefore, the decimal value is 1 × 16 + 10 × 1 = 26.
Comment