将HEX转换为DEC

时间:2020-05-25 19:13:00

标签: c++ hex decimal

我正在尝试使用C ++程序将十六进制值转换为十进制值。只是无法提供有效的代码。

这是我想出的最好的事情:

int main () {
    string link;
    string hex_code;
    int dec_code;
    int i;
    int n = 6;
    int num;
    int hex;

    cout << "Insert 1 of the HEX characters at a time:";

    for (i = 0; i < n; i++) {
        cin >> hex_code;
    }
    for (i = 0; i < n; i++) {
        if (hex_code == "A") {
            hex_code = 10;
        }
        else if (hex_code == "B") {
            hex_code = 11;
        }
        else if (hex_code == "C") {
            hex_code = 12;
        }
        else if (hex_code == "D") {
            hex_code = 13;
        }
        else if (hex_code == "E") {
            hex_code = 14;
        }
        else if (hex_code == "F") {
            hex_code = 15;
        }
        else {
            hex_code = hex_code;
        }
        num = hex * pow (16, i);
    }
    for (i = 0; i < n; i++) {
        dec_code = dec_code + num;
    }
    cout << dec_code;
return 0;
}

欢迎任何帮助/反馈/意见。

编辑:谢谢您的所有帮助。在这里找到了我尝试创建的代码,但失败了:https://stackoverflow.com/a/27334556/13615474

3 个答案:

答案 0 :(得分:0)

C ++的iomanip库中有一个十六进制操纵器

   cout << "Insert 1 of the HEX characters at a time:";

    for (i = 0; i < n; i++) {
        int hexcode;
        std::cin >> std::hex >> hexcode;
        std::cout << hexcode << std::endl;
    }

这将打印给定十六进制代码的十进制等效值

答案 1 :(得分:0)

十六进制到十进制的转换可以通过将输入数字读取为字符数组并对每个字符执行转换算法来实现。

以下是将十六进制转换为十进制的有效示例:

// File name: HexToDec.cpp    
#include <iostream>
#include <cstring>
using namespace std;

int hexToDec(char hexNumber[]) {
    int decimalNumber = 0;
    int len = strlen(hexNumber);
    for (int base = 1, i=(len-1); i>=0; i--, base *= 16) {
       // Get the hex digit in upper case 
       char digit = toupper(hexNumber[i]);
       if ( digit >= '0' && digit <='9' ) {
          decimalNumber += (digit - 48)*base;
       }
       else if ( digit >='A' && digit <='F' ) {
          decimalNumber += (digit - 55)*base;
       }
    }
    return decimalNumber;
}

int main() {

   char hexNumber[80];
   // Read the hexadecimal number as a character array
   cout << "Enter hexadecimal number: ";
   cin >> hexNumber;
   cout << hexNumber << " in decimal format = " << hexToDec(hexNumber) << "\n";
   return 0;
}

输出:

Enter hexadecimal number: DEC
DEC in decimal format = 3564

更多信息:

https://www.geeksforgeeks.org/program-for-hexadecimal-to-decimal/

答案 2 :(得分:0)

这是使用查找表的简单代码片段:

char c;
static const char hex_to_decimal[] = "0123456789ABCDEF";
std::cin >> c;
int decimal = 0;
for (decimal = 0; decimal < sizeof(hex_to_decimal) - 1; ++decimal)
{
  if (hex_to_decimal[i] == c)
  {
      break;
  }
}

另一种转换方法:

std::cin >> c;
int decimal;
if (is_digit(c))
{
    decimal = c - '0';
}
else
{
    decimal = 10 + c - 'A';
}

上面的代码片段假定编码具有连续的'A'...'F'。 第一个示例更具便携性。