C++: Converting Hexadecimal to Decimal

前端 未结 7 1759
一向
一向 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

    This should work as well.

    #include 
    #include 
    
    template
    T Hex2Int(const char* const Hexstr, bool* Overflow)
    {
        if (!Hexstr)
            return false;
        if (Overflow)
            *Overflow = false;
    
        auto between = [](char val, char c1, char c2) { return val >= c1 && val <= c2; };
        size_t len = strlen(Hexstr);
        T result = 0;
    
        for (size_t i = 0, offset = sizeof(T) << 3; i < len && (int)offset > 0; i++)
        {
            if (between(Hexstr[i], '0', '9'))
                result = result << 4 ^ Hexstr[i] - '0';
            else if (between(tolower(Hexstr[i]), 'a', 'f'))
                result = result << 4 ^ tolower(Hexstr[i]) - ('a' - 10); // Remove the decimal part;
            offset -= 4;
        }
        if (((len + ((len % 2) != 0)) << 2) > (sizeof(T) << 3) && Overflow)
            *Overflow = true;
        return result;
    }
    

    The 'Overflow' parameter is optional, so you can leave it NULL.

    Example:

    auto result = Hex2Int("C0ffee", NULL);
    auto result2 = Hex2Int("DeadC0ffe", NULL);
    

提交回复
热议问题