+ 1
Base conversion
Is there a function in C or C++ Standard library that converts bases? like converting decimal to octal or hex to decimal?
1 Antwort
+ 3
Yes, you can use unsigned int:
unsigned int n = 16; // decimal input unsigned int m = 0xFF; // hexadecimal input std::cout << std::dec << "Decimal: " << n << ", " << m << std::endl; std::cout << std::hex << "Hexadecimal: 0x" << n << ", 0x" << m << std::endl;
Octal is also supported, though for other bases you had best write your own algorithm - it's essentially a three-liner in C++:
std::string to_base(unsigned int n, unsigned int base) { static const char alphabet[] = "0123456789ABCDEFGHI"; std::string result; while(n) { result += alphabet[n % base]; n /= base; } return std::string(result.rbegin(), result.rend()); }
The inverse unsigned int from_base(std::string, unsigned int base) function is similar
(Not mine, StackOverflow)