C++十六進位制轉十進位制程式
給定一個十六進位制數作為輸入,任務是將給定的十六進位制數轉換為十進位制數。
計算機中的十六進位制數以16為基數表示,十進位制數以10為基數表示,並用0-9的值表示,而十六進位制數的數字從0到15開始,其中10表示為A,11表示為B,12表示為C,13表示為D,14表示為E,15表示為F。
要將十六進位制數轉換為十進位制數,請遵循以下步驟:
- 我們將從右到左提取數字(透過取餘數),然後將其乘以從0開始的冪,並增加1,直到(數字位數)-1。
- 由於我們需要進行從十六進位制到二進位制的轉換,因此冪的底數將為16,因為十六進位制的底數為16。
- 將給定輸入的數字與底數和冪相乘,並存儲結果。
- 將所有相乘的值加起來以獲得最終結果,該結果將是一個十進位制數。
下面是將十六進位制數轉換為十進位制數的圖形表示。

示例
Input-: ACD A(10) will be converted to a decimal number by -: 10 X 16^2 = 2560 C(12) will be converted to a decimal number by -: 12 X 16^1 = 192 D(13) will be converted to a decimal number by -: 13 X 16^0 = 13 Output-: total = 13 + 192 + 2560 = 2765
演算法
Start Step 1-> declare function to convert hexadecimal to decimal int convert(char num[]) Set int len = strlen(num) Set int base = 1 Set int temp = 0 Loop For int i=len-1 and i>=0 and i— IF (num[i]>='0' && num[i]<='9') Set temp += (num[i] - 48)*base Set base = base * 16 End Else If (num[i]>='A' && num[i]<='F') Set temp += (num[i] - 55)*base Set base = base*16 End return temp step 2-> In main() declare char num[] = "3F456A" Call convert(num) Stop
示例
#include<iostream>
#include<string.h>
using namespace std;
//convert hexadecimal to decimal
int convert(char num[]) {
int len = strlen(num);
int base = 1;
int temp = 0;
for (int i=len-1; i>=0; i--) {
if (num[i]>='0' && num[i]<='9') {
temp += (num[i] - 48)*base;
base = base * 16;
}
else if (num[i]>='A' && num[i]<='F') {
temp += (num[i] - 55)*base;
base = base*16;
}
}
return temp;
}
int main() {
char num[] = "3F456A";
cout<<num<<" after converting to deciaml becomes : "<<convert(num)<<endl;
return 0;
}輸出
如果我們執行以上程式碼,它將生成以下輸出
3F456A after converting to deciaml becomes : 4146538
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP