輕松實現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

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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM