1. 程式人生 > 程式設計 >輕鬆實現C/C++各種常見進位制相互轉換

輕鬆實現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,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",8));
 printf("\"A\" in hex --> %ld\n",strtol("A",16));
 printf("\"junk\" in base-36 --> %ld\n",strtol("junk",36));
 printf("\"012\" in auto-detected base --> %ld\n",strtol("012",0));
 printf("\"0xA\" in auto-detected base --> %ld\n",strtol("0xA",0));
 printf("\"junk\" in auto-detected base --> %ld\n",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

實現效果還算理想,另外,這個函式還可以把10進位制數轉化為不常用的其他進位制,不侷限於2,8,10,16等常見進位制。但是r的有效範圍應該為2-36。

另外,函式並沒有考慮負數以及浮點數,r不合法的情況

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。