将十六进制转换为DEC

问题描述 投票:0回答:2

我正在尝试使用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;
}

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

c++ hex decimal
2个回答
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;
    }

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


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/

© www.soinside.com 2019 - 2024. All rights reserved.