其它进制转为十进制
在实现这个需求之前,先简单介绍一个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; }