# Case Study: Converting a Hexadecimal Digit to a Decimal Value in C++

This section presents a program that converts a hexadecimal digit into a decimal value.

The hexadecimal number system has 16 digits: 0-9, A-F. The letters A, B, C, D, E, and F correspond to the decimal numbers 10, 11, 12, 13, 14, and 15. We now write a program that prompts the user to enter a hex digit and display its corresponding decimal value, as shown in Listing 4.6.

Listing 4.6 HexDigit2Dec.cpp

1 #include <iostream>

2 #include <cctype>

3 using namespace std;

4

5 int main()

6 {

7    cout << “Enter a hex digit: “;

8    char hexDigit;

9    cin >> hexDigit;

10

11    hexDigit = toupper(hexDigit);

12    if (hexDigit <= ‘F’ && hexDigit >= ‘A’)

13    {

14       int value = 10 + hexDigit – ‘A’;

15       cout << “The decimal value for hex digit “

16       << hexDigit << ” is ” << value << endl;

17    }

18    else if (isdigit(hexDigit))

19    {

20       cout << “The decimal value for hex digit “

21       << hexDigit << ” is ” << hexDigit << endl;

22    }

23    else

24    {

25       cout << hexDigit << ” is an invalid input” << endl;

26    }

27

28     return 0;

29 }

The program reads a hex digit as a character from the console (line 9) and obtains the upper­case letter for the character (line 11). If the character is between ‘A’ and ‘F’ (line 12), the corresponding decimal value is hexDigit – ‘A’ + 10 (line 14). Note that hexDigit – ‘A’ is 0 if hexDigit is ‘A’, hexDigit – ‘A’ is 1 if hexDigit is ‘B’, and so on. When two characters perform a numerical operation, the characters’ ASCII codes are used in the computation.

The program invokes the isdigit(hexDigit) function to check if hexDigit is between ‘0’ and ‘9’ (line 18). If so, the corresponding decimal digit is the same as hexDigit (lines 20-21).

If hexDigit is not between ‘A’ and ‘F’ nor a digit character, the program displays an error message (line 25).

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.