Added code to help convert between number bases

master
Aadhavan Srinivasan 11 months ago
parent cb958d2749
commit cb525c4097

@ -0,0 +1,48 @@
#include <string>
#include <cmath>
#include <iostream>
#include <algorithm>
std::string possible_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
/* Convert the given value from the given base, to base 10 */
int to_decimal(std::string num, int from_base) {
char current_char = 0;
int index = 0;
int value = 0;
/* Here, we convert 'num' to decimal (base 10) - Find the index of
every character in the string, in 'possible_chars' and
compute the value using */
for (int i=0; i < (int)num.length(); i++) {
current_char = num.at(i);
index = possible_chars.find(current_char);
value += pow(from_base, num.length() - i - 1) * index;
}
return value;
}
/* Convert the given value from base 10 to the given base */
std::string from_decimal(int num, int to_base) {
std::string return_val;
int val = 0;
while (num > 0) {
val = num % to_base;
return_val.push_back(possible_chars[val]);
num /= to_base;
}
/* Reverse the string, since we started from the right */
std::reverse(return_val.begin(), return_val.end());
return return_val;
}
/* Convert the given value from 'from_base', to 'to_base' */
std::string base_convert(std::string num, int from_base, int to_base) {
int temp = to_decimal(num, from_base);
std::string result = from_decimal(temp, to_base);
return result;
}
Loading…
Cancel
Save