convert hex buffer to unsigned int

ぐ巨炮叔叔 提交于 2019-12-12 03:16:38

问题


I've been trying to convert a hexadecimal number saved in a buffer to an unsigned int. However the "0x00" in front of every hexadecimal number that I'm reading from has been giving me problem, in essence the problem (in a downscaled version) looks like this:

char b[] = "0x0014A12";
std::stringstream ss;
unsigned int i;
ss << std::hex << b;
ss >> i;
cout << i << endl;

Any tips?

Note: The program outputs a high decimal nubmer which equals CCCCCC in hex.


回答1:


This works fine for me:

#include <iostream>
#include <sstream>

int main(int argc, char* argv[])
{
    using namespace std;

    string b("0x0014A12");

    stringstream ss;
    ss << hex << b;

    unsigned int dec;
    ss >> dec;

    cout << b << " = " << dec << endl;
    return 0;
}

output:

0x0014A12 = 84498



回答2:


The following works for me:

char b[] = "0x0014A12";
unsigned int i;
sscanf(b, "%X", &i);



回答3:


I prefer sscanf for this kind of problem.

sscanf(b, "0x%x", &i);


来源:https://stackoverflow.com/questions/9031439/convert-hex-buffer-to-unsigned-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!