用于在十进制和任意基数之间转换的c ++模板

时间:2012-01-15 13:51:50

标签: c++ algorithm numbers base-conversion

是否有c ++结构或模板(在任何库中)允许我在十进制和任何其他基础之间进行转换(就像bitset可以做的那样)?

1 个答案:

答案 0 :(得分:5)

是的,您可以使用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,但对于其他基础你最好编写自己的算法 - 它本质上是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)函数类似。