-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathhexadecimal.cpp
86 lines (75 loc) · 2.08 KB
/
hexadecimal.cpp
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <sstream>
#include <string>
#include <stdexcept>
using namespace std;
namespace mlb
{
// Function to convert decimal to hexadecimal
string decimalToHex(int decimalNumber)
{
stringstream ss;
ss << hex << uppercase << decimalNumber;
return ss.str();
}
// Function to convert hexadecimal to decimal
int hexToDecimal(const string &hexStr)
{
int decimalNumber;
stringstream ss(hexStr);
ss >> hex >> decimalNumber;
return decimalNumber;
}
// Function to add two hexadecimal numbers
string hexAdd(const string &hex1, const string &hex2)
{
int num1 = hexToDecimal(hex1);
int num2 = hexToDecimal(hex2);
int sum = num1 + num2;
return decimalToHex(sum);
}
// Function to subtract two hexadecimal numbers
string hexSub(const string &hex1, const string &hex2)
{
int num1 = hexToDecimal(hex1);
int num2 = hexToDecimal(hex2);
return decimalToHex(num1 - num2);
}
// Function to multiply two hexadecimal numbers
string hexMul(const string &hex1, const string &hex2)
{
int num1 = hexToDecimal(hex1);
int num2 = hexToDecimal(hex2);
return decimalToHex(num1 * num2);
}
// Function to divide two hexadecimal numbers
string hexDiv(const string &hex1, const string &hex2)
{
int num1 = hexToDecimal(hex1);
int num2 = hexToDecimal(hex2);
if (num2 == 0)
{
throw invalid_argument("Division by zero is not allowed.");
}
return decimalToHex(num1 / num2);
}
string hexAdd(int num1, int num2)
{
return decimalToHex(num1 + num2);
}
string hexSub(int num1, int num2)
{
return decimalToHex(num1 - num2);
}
string hexMul(int num1, int num2)
{
return decimalToHex(num1 * num2);
}
string hexDiv(int num1, int num2)
{
if (num2 == 0)
{
throw invalid_argument("Division by zero is not allowed.");
}
return decimalToHex(num1 / num2);
}
};