#include <iostream>
#include <stdlib.h>
#include <string>
#include <ctime>
using namespace std;
class Hex
{
private:
string hexadecimal = "0";
int decimal = 0;
public:
Hex() = default;
~Hex() = default;
Hex(const string& hex) : hexadecimal(hex), decimal(HexToDec(hex)) {}
Hex(const int& dec) :hexadecimal(DecToHex(dec)), decimal(dec){}
string DecToHex(const int& num);
int HexToDec(const string& hex);
int CharToInt(const char& c);
Hex operator+(const Hex& h);
friend ostream& operator<<(ostream& os, const Hex& h);
};
string Hex::DecToHex(const int& num)
{
string str;
int Temp = num / 16;
int left = num % 16;
if (Temp > 0)
str += DecToHex(Temp);
if (left < 10)
str += (left + '0');
else
str += ('a' + left - 10);
return str;
}
int Hex::HexToDec(const string& hexString)
{
int result = 0;
int len = hexString.size();
for (int i = 0; i < len; i++)
{
result += pow(16, len - i - 1) * CharToInt(hexString[i]);
}
return result;
}
int Hex::CharToInt(const char& c)
{
if (c >= '0' && c <= '9')
return c - '0';
else if (c >= 'a' && c <= 'f')
return (c - 'a' + 10);
else if (c >= 'A' && c <= 'F')
return (c - 'A' + 10);
assert(0);
return 0;
}
Hex Hex::operator+(const Hex& h)
{
int temp_decimal = decimal + h.decimal;
return Hex(temp_decimal);
}
ostream& operator<<(ostream& os, const Hex& h)
{
os << "HexStr: " << h.hexadecimal << " DecimalInt: " << h.decimal;
return os;
}
C++ 16进制数和10进制数的转换类
最新推荐文章于 2024-02-19 17:50:29 发布