简体   繁体   English

将字节的字符串转换为无符号的int

[英]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). 对于我要编写的应用程序,我需要能够在接口中编写GLEnable(GL_REPEAT)(完成此工作)。 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. 但参数为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. 为了获得正确的参数,我将glew.h文件读取为文本文件,并将其解析为std :: map。 However, I am stuck on how to convert 0x2901 (and the rest) from a string to an unsigned int. 但是,我对如何将0x2901(及其余)从字符串转换为无符号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::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 解析值:10497
Should be 10497 应该是10497

Live Demo 现场演示

You can try also C style ( sscanf function), like that: 您也可以尝试使用C样式( sscanf函数),如下所示:

    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: sscanf允许检查以下样式:

    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");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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