温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用C/C++怎么实现进制相互转换

发布时间:2021-06-02 16:51:29 来源:亿速云 阅读:147 作者:Leah 栏目:编程语言

这期内容当中小编将会给大家带来有关使用C/C++怎么实现进制相互转换,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

其它进制转为十进制

在实现这个需求之前,先简单介绍一个c标准库中的一个函数:

long strtol( const char *str, char **str_end, int base);

参数详细说明请 参考文档

注意:这个函数在c标准库stdlib中,所以需要 #include<cstdlib>

用法参考

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
 
int main(void)
{
 // parsing with error handling
 const char *p = "10 200000000000000000000000000000 30 -40 junk";
 printf("Parsing '%s':\n", p);
 char *end;
 for (long i = strtol(p, &end, 10);p != end;i = strtol(p, &end, 10))
 {
 printf("'%.*s' -> ", (int)(end-p), p);
 p = end;
 if (errno == ERANGE){
  printf("range error, got ");
  errno = 0;
 }
 printf("%ld\n", i);
 }
 
 // parsing without error handling
 printf("\"1010\" in binary --> %ld\n", strtol("1010",NULL,2));
 printf("\"12\" in octal --> %ld\n", strtol("12",NULL,8));
 printf("\"A\" in hex --> %ld\n", strtol("A",NULL,16));
 printf("\"junk\" in base-36 --> %ld\n", strtol("junk",NULL,36));
 printf("\"012\" in auto-detected base --> %ld\n", strtol("012",NULL,0));
 printf("\"0xA\" in auto-detected base --> %ld\n", strtol("0xA",NULL,0));
 printf("\"junk\" in auto-detected base --> %ld\n", strtol("junk",NULL,0));
}

Output

Parsing '10 200000000000000000000000000000 30 -40 junk':
'10' -> 10
' 200000000000000000000000000000' -> range error, got 9223372036854775807
' 30' -> 30
' -40' -> -40
"1010" in binary --> 10
"12" in octal --> 10
"A" in hex --> 10
"junk" in base-36 --> 926192
"012" in auto-detected base --> 10
"0xA" in auto-detected base --> 10
"junk" in auto-detected base --> 0

更多详细说明请 参考文档

接下来使用这个函数来实现其它进制转为十进制的需求,具体请参考代码:

#include<iostream>
#include<cstdlib>
using namespace std;
int main(){
 //把8进制的17转化为10进制打印输出
 string str = "17";
 char *tmp ;
 long result = strtol(str.c_str(),&tmp,8);
 cout<<result;
 return 0;
}

Output

15

十进制转为其他进制

目前没有找到可以使用的库函数来方便的实现这个需求,所以自己实现了一下,具体请参考代码:

#include<iostream>
#include<algorithm>
using namespace std;
//digital为10进制数,r为需要转换的目标进制,返回目标进制数
string dtox(int digital,int r){
 string result="";
 const char s[37]="0123456789abcdefghijklmnopqrstuvwxyz";
 if(digital==0){
 return "0";
 }
 while(digital!=0){
 int tmp =digital%r;
 result+=s[tmp];
 digital/=r;
 }
 reverse(result.begin(),result.end());
 return result;
}
int main(){
 cout<<"十进制10转为16进制结果:"<<dtox(10,16)<<endl;
 cout<<"十进制10转为8进制结果:"<<dtox(10,8)<<endl;
 cout<<"十进制10转为2进制结果:"<<dtox(10,2)<<endl;
 cout<<"十进制10转为10进制结果:"<<dtox(10,10)<<endl;
}

Output:

十进制10转为16进制结果:a
十进制10转为8进制结果:12
十进制10转为2进制结果:1010
十进制10转为10进制结果:10

上述就是小编为大家分享的使用C/C++怎么实现进制相互转换了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI