C ++模板的十进制和任意进制之间的转换 [英] c++ template for conversion between decimal and arbitrary base

查看:391
本文介绍了C ++模板的十进制和任意进制之间的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个C ++结构或模板(在任何库),可以让我做的十进制和任何其他基(更象是位集可以做的)之间的转换?

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) ?

推荐答案

是的,你可以使用无符号整型

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:

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());
}

无符号整数from_base(标准::字符串,无符号整型基地)的功能是相似的。

这篇关于C ++模板的十进制和任意进制之间的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆