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

轻松实现C/C++各种常见进制相互转换

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

轻松实现C/C++各种常见进制相互转换

其它进制转为十进制

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

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

参数详细说明请 参考文档

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

用法参考

#include 
#include 
#include 
 
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("%ldn", i);
 }
 
 // parsing without error handling
 printf(""1010" in binary --> %ldn", strtol("1010",NULL,2));
 printf(""12" in octal --> %ldn", strtol("12",NULL,8));
 printf(""A" in hex --> %ldn", strtol("A",NULL,16));
 printf(""junk" in base-36 --> %ldn", strtol("junk",NULL,36));
 printf(""012" in auto-detected base --> %ldn", strtol("012",NULL,0));
 printf(""0xA" in auto-detected base --> %ldn", strtol("0xA",NULL,0));
 printf(""junk" in auto-detected base --> %ldn", 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
#include
using namespace std;
int main(){
 //把8进制的17转化为10进制打印输出
 string str = "17";
 char *tmp ;
 long result = strtol(str.c_str(),&tmp,8);
 cout<

Output

15

十进制转为其他进制

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

#include
#include
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进制结果:"<

Output:

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

实现效果还算理想,另外,这个函数还可以把10进制数转化为不常用的其他进制,不局限于2,8,10,16等常见进制。但是r的有效范围应该为2-36。

另外,函数并没有考虑负数以及浮点数,r不合法的情况

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

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

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

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