Created
May 17, 2016 14:08
-
-
Save 1995eaton/9767aa80874282295196c32c76e156eb to your computer and use it in GitHub Desktop.
to_base
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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