Skip to content

Instantly share code, notes, and snippets.

@hassaananjum
Created July 29, 2015 06:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hassaananjum/097ae03e1c09c446ce2d to your computer and use it in GitHub Desktop.
Save hassaananjum/097ae03e1c09c446ce2d to your computer and use it in GitHub Desktop.
#include <string.h>
#include <bitset>
#include <iostream>
std::string hex_to_binary(std::string hexstring){
static char base16encoding_table[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
std::string binstring;
for( int i = 0; i < hexstring.length(); i++){
binstring += std::bitset<4>((int)(strchr(base16encoding_table,hexstring[i]) - base16encoding_table)).to_string();
}
return binstring;
}
std::string binary_to_b64(std::string binstring){
static char base64encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
std::string b64string;
for(int i = 0; i < binstring.length(); i+=6){
int end = i+6;
std::string charstring = binstring.substr(i,end);
int newint = std::bitset<6>(charstring).to_ulong();
b64string += base64encoding_table[newint];
}
return b64string;
}
std::string hex_2_b64(std::string hexstring){
return binary_to_b64(hex_to_binary(hexstring));
}
int main(int argc, char** argv){
if(argc < 2){
std::cout<<"USAGE:"<<std::endl;
std::cout<<"hex2b64 <hex string>"<<std::endl;
}
else{
std::string hexstring(argv[1]);
std::cout<<"HEX String : "<<hexstring<<std::endl;
std::cout<<"B64 Srting : "<<hex_2_b64(hexstring)<<std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment