是否有允许我在十进制和任何其他基础之间进行转换的 c++ 结构或模板(在任何库中)(就像 bitset 可以做的那样)?
2778 次
1 回答
6
是的,您可以使用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;
也支持八进制,但对于其他基础,您最好编写自己的算法 - 它本质上是 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());
}
反unsigned int from_base(std::string, unsigned int base)
函数类似。
于 2012-01-15T13:57:06.090 回答