string _hex2bits(char s)
{
int num;
if ('0' <= s && s <= '9'){
num = s - '0';
} else{
num = s - 'A' + 10;
}
string str;
for (int i = 0; i < 8; i++)
{
int mod = num % 2;
str.push_back('0' + mod);
num = num / 2;
}
reverse(str.begin(), str.end());
return str;
}
int _bits2num(string& str)
{
int result = 0;
int base = 1;
for (int i = str.length()-1; i >= 0; i--) {
if (str[i] == '1'){
result += base;
}
base *= 2;
}
return result;
}
char _num2char(int num)
{
assert(num >= 0 && num <= 63);
if (0 <= num && num <= 25)
{
return 'A' + (num - 0);
}
else if (26 <= num && num <= 51)
{
return 'a' + (num - 26);
}
else if (52 <= num && num <= 61)
{
return '0' + (num - 52);
}
else if (num == 62)
{
return '+';
}
else
{
return '//';
}
}
void hex2base64(string& str)
{
transform(str.begin(), str.end(), str.begin(), ::toupper);
int mod = str.length() % 3;
mod = mod == 0 ? -1 : 3 - mod;
string tmp;
for (int i = 0; i < str.length(); i++){
tmp += _hex2bits(str[i]);
}
for (int i = 0; i+6 <= tmp.length(); i = i+6)
{
string base64bits = tmp.substr(i, 6);
int num = _bits2num(base64bits);
cout << _num2char(num);
}
for (int i = 0; i < mod+1; i++)
{
cout << '=';
}
}
int main()
{
string test1 = "1A2";
hex2base64(test1);
return 0;
}