Convert a hexadecimal string to an integer efficiently in C?

后端 未结 16 2109
暖寄归人
暖寄归人 2020-12-01 09:31

In C, what is the most efficient way to convert a string of hex digits into a binary unsigned int or unsigned long?

For example, if I have

16条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 10:06

    This currently only works with lower case but its super easy to make it work with both.

    cout << "\nEnter a hexadecimal number: ";
    cin >> hexNumber;
    orighex = hexNumber;
    
    strlength = hexNumber.length();
    
    for (i=0;i="0") && (hexa<="9"))
        {
            //cout << "This is a numerical value.\n";
        }
        else
        {
            //cout << "This is a alpabetical value.\n";
            if (hexa=="a"){hexa="10";}
            else if (hexa=="b"){hexa="11";}
            else if (hexa=="c"){hexa="12";}
            else if (hexa=="d"){hexa="13";}
            else if (hexa=="e"){hexa="14";}
            else if (hexa=="f"){hexa="15";}
            else{cout << "INVALID ENTRY! ANSWER WONT BE CORRECT\n";}
        }
        //convert from string to integer
    
        hx = atoi(hexa.c_str());
        finalhex = finalhex + (hx*pow(16.0,strlength-i-1));
    }
    cout << "The hexadecimal number: " << orighex << " is " << finalhex << " in decimal.\n";
    

提交回复
热议问题