任意进制的转换

1. 十进制转为任意进制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<stdio.h>
int main()
{
    int a,b,count=0,i;
    scanf("%d%d",&a,&b);  //a为需要转换的十进制数,b为需要转换成的进制数
    int arr[100];
    do
    {
      arr[count++]=a%b;  //比如说100转换为8进制:100%8=4,100/8=12,12%8=4,12/8=1;1%8=1,1/8=0;通过观察 1 4 4组成的144就是100转换为8进制后的数
      a=a/b;
     } while(a!=0);
     for(i=count-1;i>=0;i--)
     {
        printf("%d",arr[i]);   // 如果是 16 进制转换,还需将数字替换为字符
     }
 }

2. 直接使用C++函数进行转换

1
2
3
4
5
6
7
#include <iostream>
using namespace std;
int main()
{   cout << "35的8进制:" << oct << 35 << endl;    // 八进制octonary       <<____<<num    ____里面选择需要转换为八进制的oct ,num为需要被转换的数
    cout << "35的10进制" << dec << 35 << endl;    //十进制decimalism      <<____<<num    ____里面选择需要转换为十进制的dec ,num为需要被转换的数
    cout << "35的16进制:" << hex << 35 << endl;   //十六进制hexadecimal    <<____<<num    ____里面选择需要转换为十六进制的hex,num为需要被转换的数
}

3. 调用bitset函数将十进制数转换为二进制 

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <bitset>
using namespace std;  
                       //定义:bitset< n > s;
                       //表示一个n位的二进制数,<>中填写位数;默认()中的数为十进制 
int main()
{   cout << "35的2进制(显示8位):" << bitset<8>(35) << endl;
    cout << "35的2进制(显示18位):" << bitset<18>(35) << endl;  //在<_>中,__横线上填写转换为二进制后需要显示的位数 ()内写需要被转换成二进制的数
    cout << "35的2进制(显示3位):" << bitset<3>(35) << endl; //注意:在使用这个函数前需要调用头文件 #include <bitset>
}

4. _itoa函数能将十进制数转换为任意进制的数

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <algorithm>//需要调用这个头文件
using namespace std;
int main()
{  
  
    // 将10进制数转换为任意的n进制数,结果为char型。
    int num = 233;
    char buffer[100]; //例如,将十进制的数字233转换为8进制的数字  351
    _itoa(num, buffer, 8);  //c++中一般用_itoa,用itoa也行,
    cout << buffer;
}

_itoa() 是线程不安全的,建议使用 _itoa_s()  、

 

5. 十进制数转为十六进制大写字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
 
void test()
{
    int res;
    cin >> res;
    string ans = "";
    int tot = 0;
 
     while (res) {
          if (res % 16 > 9) {
               ans = char(res % 16 - 9 + 64) + ans;   // 大写十六进制字符
          } else {
               ans = to_string(res % 16) + ans;
          }
               res /= 16;
     }
}

  

posted @   皮卡啰  阅读(470)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤
点击右上角即可分享
微信分享提示