C++: Converting Hexadecimal to Decimal

前端 未结 7 1752
一向
一向 2020-11-30 11:49

I\'m looking for a way to convert hex(hexadecimal) to dec(decimal) easily. I found an easy way to do this like :



        
7条回答
  •  旧巷少年郎
    2020-11-30 12:03

    Here is a solution using strings and converting it to decimal with ASCII tables:

    #include 
    #include 
    #include "math.h"
    using namespace std;
    unsigned long hex2dec(string hex)
    {
        unsigned long result = 0;
        for (int i=0; i=48 && hex[i]<=57)
            {
                result += (hex[i]-48)*pow(16,hex.length()-i-1);
            } else if (hex[i]>=65 && hex[i]<=70) {
                result += (hex[i]-55)*pow(16,hex.length( )-i-1);
            } else if (hex[i]>=97 && hex[i]<=102) {
                result += (hex[i]-87)*pow(16,hex.length()-i-1);
            }
        }
        return result;
    }
    
    int main(int argc, const char * argv[]) {
        string hex_str;
        cin >> hex_str;
        cout << hex2dec(hex_str) << endl;
        return 0;
    }
    

提交回复
热议问题