Skip to content

Instantly share code, notes, and snippets.

@Arnau478
Created February 5, 2025 10:50
Show Gist options
  • Save Arnau478/41aba38f272a2a718b78e8f9ca55958a to your computer and use it in GitHub Desktop.
Save Arnau478/41aba38f272a2a718b78e8f9ca55958a to your computer and use it in GitHub Desktop.
Number basis change
string basis_change(string source, int from, int to) {
assert(from >= 2 && from <= 16);
assert(to >= 2 && to <= 16);
long long num = 0;
int power = 0;
bool negative = false;
for (int i = source.length() - 1; i >= 0; i--) {
char c = toupper(source[i]);
int digit = 0;
if (i == 0 && c == '-') {
negative = true;
continue;
}
if (c >= '0' && c <= '9') {
digit = c - '0';
} else if (c >= 'A' && c <= 'F') {
digit = c - 'A' + 10;
}
num += digit * pow(from, power++);
}
if (num == 0) {
return "0";
}
string result;
while (num > 0) {
int remainder = num % to;
char digit;
if (remainder < 10) {
digit = '0' + remainder;
} else {
digit = 'A' + (remainder - 10);
}
result.push_back(digit);
num /= to;
}
if (negative) result.push_back('-');
reverse(result.begin(), result.end());
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment