You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
1.6 KiB
C++
55 lines
1.6 KiB
C++
#include "includes/numeric_base.hpp"
|
|
#include <string>
|
|
#include <cmath>
|
|
#include <cctype>
|
|
#include <algorithm>
|
|
|
|
std::string possible_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
|
|
|
unsigned int to_decimal(std::string num, int from_base) {
|
|
char current_char = 0;
|
|
int index = 0;
|
|
unsigned 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 the position of the character in the number. */
|
|
for (int i=0; i < (int)num.length(); i++) {
|
|
current_char = num.at(i);
|
|
index = possible_chars.find(toupper(current_char)); // Convert the character to upper-case, so that the earliest match is detected
|
|
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(unsigned int num, int to_base) {
|
|
std::string return_val;
|
|
int val = 0;
|
|
/* Handle the special case of num being zero: In this case, the result is also zero */
|
|
if (num == 0) {
|
|
return_val = "0";
|
|
} else {
|
|
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) {
|
|
unsigned int temp = to_decimal(num, from_base);
|
|
std::string result = from_decimal(temp, to_base);
|
|
|
|
return result;
|
|
}
|
|
|