-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWeek_6.cpp
More file actions
47 lines (39 loc) · 1.02 KB
/
Copy pathWeek_6.cpp
File metadata and controls
47 lines (39 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <string>
#include <cctype>
#include <stdexcept> // For std::invalid_argument
using namespace std;
int hex2Dec(const string& hex);
int hexCharToDecimal(char ch);
int main()
{
cout << "Enter a hex number: ";
string hex;
cin >> hex;
try {
cout << "The decimal value for hex number " << hex
<< " is " << hex2Dec(hex) << endl;
} catch (const invalid_argument& e) {
cerr << "Error: " << e.what() << endl;
}
return 0;
}
int hex2Dec(const string& hex)
{
int decimalValue = 0;
for (unsigned i = 0; i < hex.size(); i++) {
decimalValue = decimalValue * 16 + hexCharToDecimal(hex[i]);
}
return decimalValue;
}
int hexCharToDecimal(char ch)
{
ch = toupper(ch);
if (ch >= '0' && ch <= '9') {
return ch - '0';
} else if (ch >= 'A' && ch <= 'F') {
return 10 + ch - 'A';
} else {
throw invalid_argument(string("Invalid hex character: ") + ch);
}
}