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

更新于: 2019年10月18日

3K+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.