Skip to content

Instantly share code, notes, and snippets.

@1995eaton
Created May 17, 2016 14:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save 1995eaton/9767aa80874282295196c32c76e156eb to your computer and use it in GitHub Desktop.
Save 1995eaton/9767aa80874282295196c32c76e156eb to your computer and use it in GitHub Desktop.
to_base
#include <iostream>
template <typename T, typename U = typename std::make_unsigned<T>::type>
std::string to_base(T _n, int base) {
static const char *base_vals = "0123456789"
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static char buf[8 * sizeof (U) + 1];
U n = _n;
int i = 8 * sizeof (U);
do {
buf[--i] = base_vals[n % base];
} while (n /= base);
return std::string(buf + i);
}
int main(int argc, char **argv) {
if (argc != 3) {
std::cerr << "Usage: " << argv[0] << " <NUMBER> <BASE>\n";
return 1;
}
uint64_t n = std::stoul(argv[1]);
int base = std::stoi(argv[2]);
std::cout << n << ": " << to_base(n, base) << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment