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
  • 16
  • 3
    `char b = { 0x0014A12 };` - do you have 32bit chars on your platform? – Mat Jan 27 '12 at 09:51
  • @Mat It's a typo in the example, but thanks for pointing it out. As I wrote in the post it's saved in a buffer in the actual program. – Andreas Jan 27 '12 at 09:53
  • http://stackoverflow.com/a/1070499/1168156 – LihO Jan 27 '12 at 09:54
  • 1
    @Andreas: your fix doesn't "fix" anything. You still need at least 17bit chars for that initializer to be valid. – Mat Jan 27 '12 at 09:58

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
  • 41,190
  • 11
  • 99
  • 167
  • 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,216
  • 2
  • 34
  • 46
0

I prefer sscanf for this kind of problem.

sscanf(b, "0x%x", &i);
Tom Whittock
  • 4,081
  • 19
  • 24