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进制。

格式 进制
dec 10进制
oct 8进制
hex 16进制
#include
using namespace std;
int main() {
    int x;
    cin >> x;
    cout << oct << x << "\n\n";//10转8

    cin >> oct >> x;
    cout << hex << x << "\n\n";//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<num.size();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;
}

你可能感兴趣的:(leetcode,算法,C++常用知识点,c++,算法)