简体   繁体   中英

Converting a string of a byte to an unsigned int

For an application I'm trying to write I need to be able to write GLEnable(GL_REPEAT) in an interface (got this working). Once the user does that, the system should call the function with the correct parameter.

So far, I've got the correct function being called

((void (*)(unsigned int)) FunctionName)(Parameter); but with the parameter of 0.

In order to get the correct parameter, I am reading the glew.h file as a text file, and parsing it into an std::map. However, I am stuck on how to convert 0x2901 (and the rest) from a string to an unsigned int. If anyone happens to know how to do this, help would be greatly appreciated :)

Thanks in advance,

Joey

Perhaps you could use a std::stringstream :

std::string hexString = "0x2901";
std::istringstream instream(hexString);
unsigned int receiver = 0;
instream >> std::hex >> receiver;
std::cout << "Value parsed: " << receiver << std::endl;
std::cout << "Should be 10497" << std::endl;

Output:

Value parsed: 10497
Should be 10497

Live Demo

You can try also C style ( sscanf function), like that:

    std::string hex = "0x2901";
    unsigned int x;
    sscanf(hex.c_str(), "%x", &x);
    printf("%#X = %u\n", x, x);

sscanf allows checking in the following style:

    std::string hex = "0x2901";
    unsigned int x = 0;
    if ( sscanf(hex.c_str(), "%x", &x) == 1) 
    {
        printf("%#X = %u\n", x, x);
    }
    else
    {
        printf("Incorrect string value\n");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM