【发布时间】:2012-02-10 19:27:05
【问题描述】:
是否有 c++ 结构或模板(在任何库中)允许我在十进制和任何其他基数之间进行转换(很像 bitset 可以做的)?
【问题讨论】:
-
在编译时转换,还是在运行时转换?
-
您的意思是将任意基数中的用户定义文字转换为base10吗?
标签: c++ algorithm numbers base-conversion
是否有 c++ 结构或模板(在任何库中)允许我在十进制和任何其他基数之间进行转换(很像 bitset 可以做的)?
【问题讨论】:
标签: c++ algorithm numbers base-conversion
是的,你可以使用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) 的逆函数类似。
【讨论】:
from_base<6, intliteral_in_base_6>::value之类的事情。
kth 数字(从 0 开始)表示的值是 ((n / base^k) % base) * base^k,因此您可以将某个数字“设置为零”并将其移动到其他位置等。