c++ template for conversion between decimal and arbitrary base

…衆ロ難τιáo~ 提交于 2019-12-02 05:01:44

问题


Is there a c++ structure or template (in any library) that allows me to do conversion between decimal and any other base (much like what bitset can do) ?


回答1:


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.



来源:https://stackoverflow.com/questions/8870121/c-template-for-conversion-between-decimal-and-arbitrary-base

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!