Skip to content

Instantly share code, notes, and snippets.

@Sam-Belliveau
Created December 11, 2017 17:35
Show Gist options
  • Save Sam-Belliveau/348aecf02f8103b50f5e29304ea7229c to your computer and use it in GitHub Desktop.
Save Sam-Belliveau/348aecf02f8103b50f5e29304ea7229c to your computer and use it in GitHub Desktop.
#include <string>
std::string convert(const unsigned short sBase, const std::string in, const unsigned short oBase){
if(sBase > 92 || oBase > 92){ return "Base Is Too High!"; }
if(sBase < 2 || oBase < 2){ return "Base Is Too Low!"; }
#define ERR 255
const unsigned short CHAR_TO_NUM[128] {ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,ERR,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,0,1,2,3,4,5,6,7,8,9,77,78,79,80,81,82,83,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,83,84,85,86,87,88,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,88,89,90,91,ERR};
const char NUM_TO_CHAR[92] = {48,49,50,51,52,53,54,55,56,57,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,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,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,58,59,60,61,62,63,91,92,93,94,95,123,124,125,126};
unsigned __int128 input = 0; // Int Version Of Input
std::string out; // Output String
unsigned __int128 baseValue = 1;
const unsigned short IL = in.length();
for(unsigned short i = IL - 1; i < IL; i--){
if(CHAR_TO_NUM[in[i]] > sBase) { return "Invalid Character"; }
input += CHAR_TO_NUM[in[i]] * baseValue;
baseValue *= sBase; // Multiply Modifier
}
while(input != 0){
const unsigned short r = input%oBase;
out = NUM_TO_CHAR[r] + out;
input = (input - r) / oBase; // Divide And Round Down
}
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment