Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple algorithm to convert a hexadecimal string to a base64 string.
#include <iostream>
#include <map>
#include <string>
#include <bitset>
std::string hex_to_bin(std::string hex_str);
std::string bin_to_base64(std::string bin_str);
std::string hex_to_base64(std::string hex_str);
int main()
{
std::string hex_str;
std::cin >> hex_str;
std::cout << hex_to_base64(hex_str) << '\n';
}
std::string hex_to_base64(std::string hex_str)
{
std::string bin_str = hex_to_bin(hex_str);
return bin_to_base64(bin_str);
}
std::string hex_to_bin(std::string hex_str)
{
std::map<char,int> hex_table{ {'0',0}, {'1',1}, {'2',2}, {'3',3}, {'4',4}, {'5',5}, {'6',6}, {'7',7}, {'8',8},
{'9',9}, {'a',10}, {'b',11}, {'c',12}, {'d',13}, {'e',14}, {'f',15}};
std::string bit_str;
for(char hex_char : hex_str)
bit_str += std::bitset<4>(hex_table[hex_char]).to_string();
return bit_str;
}
std::string bin_to_base64(std::string bin_str)
{
char base64_table[] = {65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118,
119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47};
std::string base64_str;
auto bit = begin(bin_str);
while( bit != end(bin_str) )
{
std::string base64_part_str;
int bit_counter{6};
while(bit_counter-- && bit != end(bin_str) )
{
base64_part_str += *bit++;
}
int index = std::stoi(base64_part_str,nullptr,2);
base64_str += base64_table[index];
}
return base64_str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.