繁体   English   中英

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

[英]c++ template for conversion between decimal and arbitrary base

是否有一个c ++结构或模板(在任何库中)可以让我在十进制和任何其他基数之间进行转换(就像位集可以做什么)?

是的,您可以使用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)函数相似。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM