栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++进制转换

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++进制转换

目录
    • 进制转换方法
    • C++实现进制转换
      • 1. 字符串流sstream
      • 2. stoi 将 n 进制的字符串转化为十进制
      • 3.bistset库
    • 任意进制转换

进制转换方法
  • https://www.cnblogs.com/gaizai/p/4233780.html#_labelConvert21
C++实现进制转换 1. 字符串流sstream
  • https://juejin.cn/post/6935691777101791262
  • https://blog.csdn.net/weixin_43164603/article/details/103704009

c++的与c类似,也可以直接读写8进制和16进制。

格式进制
dec10进制
oct8进制
hex16进制
#include
using namespace std;
int main() {
    int x;
    cin >> x;
    cout << oct << x << "nn";//10转8

    cin >> oct >> x;
    cout << hex << x << "nn";//8转16

    cin >> hex >> x;
    cout << dec << x;//16转10

    return 0;
}
2. stoi 将 n 进制的字符串转化为十进制
  • https://www.cnblogs.com/Anber82/p/11351833.html
    需要#include《string>

stoi(字符串,起始位置,n进制),将 n 进制的字符串转化为十进制
示例:
stoi(str, 0, 2); //将字符串 str 从 0 位置开始到末尾的 2 进制转换为十进制

3.bistset库
  • https://www.jb51.net/article/158006.html
任意进制转换
#include
using namespace std;
typedef long long ll;
string trans(string num ,int from ,int to) { //num待转换数,from和to表示进制
    ll tmp, ten = 0;
    string ans;
    char c;
    for(int i=0;i  //from进制转换为10进制
        ten *= from;
        if (num[i] >= '0' && num[i] <= '9')
            tmp = num[i] - '0';
        else tmp = num[i] - 'a' + 10;
        ten += tmp;
    }
    //cout << ten << "n";
    while (ten) {   //10进制转换为to进制
        tmp = ten % to;
        c = tmp < 10 ? tmp + '0' : tmp - 10 + 'a';
        ans += c;
        ten /= to;
    }
    reverse(ans.begin(), ans.end());
    return ans;
}
int main() {
    //测试2,8,10,16进制相互转换
    cout << trans("351306", 8, 2) << "n";
    cout << trans("946351", 10, 2) << "n";
    cout << trans("a6b816", 16, 2) << "n";
    cout << "n";

    cout << trans("101111111001", 2, 8) << "n";
    cout << trans("13541913", 10, 8) << "n";
    cout << trans("a6b8c9def", 16, 8) << "n";
    cout << "n";

    cout << trans("10000001", 2, 10) << "n";
    cout << trans("6543210", 8, 10) << "n";
    cout << trans("fe60a6b8c", 16, 10) << "n";
    cout << "n";

    cout << trans("1101010101", 2, 16) << "n";
    cout << trans("66240", 8, 16) << "n";
    cout << trans("98109813", 10, 16) << "n";

    return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1038386.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号