Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- using namespace std;
- template<typename Type> constexpr bool is_integer =
- is_same<Type, long long>::value || is_same<Type, unsigned long long>::value ||
- is_same<Type, long>::value || is_same<Type, unsigned long>::value ||
- is_same<Type, int>::value || is_same<Type, unsigned>::value ||
- is_same<Type, short>::value || is_same<Type, unsigned short>::value;
- template<typename Integer> auto convert_base(Integer number, const int base) {
- static_assert(is_integer<Integer>, "The value must be an integer type!");
- const char digits[] = "0123456789ABCDEF";
- string box;
- auto save = number;
- if (number < 0) {
- auto type = string(typeid(number).name());
- if (type == "short"s) {
- auto n = static_cast<unsigned short>(abs(numeric_limits<Integer>::min() - number)) + numeric_limits<Integer>::max() + 1;
- while (n) {
- box = digits[n % base] + box;
- n /= base;
- }
- }
- if (type == "int"s) {
- auto n = static_cast<unsigned>(abs(numeric_limits<Integer>::min() - number)) + numeric_limits<Integer>::max() + 1;
- while (n) {
- box = digits[n % base] + box;
- n /= base;
- }
- }
- if (type == "long"s) {
- auto n = static_cast<unsigned long>(abs(numeric_limits<Integer>::min() - number)) + numeric_limits<Integer>::max() + 1;
- while (n) {
- box = digits[n % base] + box;
- n /= base;
- }
- }
- if (type == "__int64"s) {
- auto n = static_cast<unsigned __int64>(abs(numeric_limits<Integer>::min() - number)) + numeric_limits<Integer>::max() + 1;
- while (n) {
- box = digits[n % base] + box;
- n /= base;
- }
- }
- } else {
- while (number) {
- box = digits[number % base] + box;
- number /= base;
- }
- }
- if (base == 2) box = "0b" + box;
- else if (base == 8) box = '0' + box;
- else if (base == 16) box = "0x" + box;
- else box = to_string(save);
- return box;
- }
- int main() {
- long a = 127;
- auto ab = convert_base(a, 2);
- auto ao = convert_base(a, 8);
- auto ah = convert_base(a, 16);
- cout << ab << '\n' << ao << '\n' << ah << '\n';
- long long b = -127;
- auto bb = convert_base(b, 2);
- auto bo = convert_base(b, 8);
- auto bh = convert_base(b, 16);
- cout << bb << '\n' << bo << '\n' << bh << '\n';
- auto x = 555;
- auto xx = convert_base(x, 12);
- cout << xx << '\n';
- cin.get();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement