0

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.

Andreas
  • 541
  • 2
  • 8
  • 15

3 Answers3

4

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
LihO
  • 39,598
  • 10
  • 94
  • 164
  • Works fine for me too, I kind of messed up the example, and the conversion was not the actual problem in the program, but rather the memory of the stored hexadecimals were corrupt. Should've thought some more before asking the question, but thanks for the answer, this works for me too. – Andreas Jan 27 '12 at 10:09
1

The following works for me:

char b[] = "0x0014A12";
unsigned int i;
sscanf(b, "%X", &i);
Peter
  • 7,106
  • 2
  • 33
  • 46
0

I prefer sscanf for this kind of problem.

sscanf(b, "0x%x", &i);
Tom Whittock
  • 3,981
  • 18
  • 23