How can I correctly convert this to hex?

101 Views Asked by At

I have an issue where I am trying to convert numbers to hex with the following code.

int numconvert(string hexnum)
{
stringstream converter(hexnum);
unsigned int value = 0;
converter >> hex >> value;
return value;
}

string hexconvert(int hexnum)
{
stringstream ss;
ss << hex << hexnum;

string n;
ss >> n;
return n;
}

I use the numconvert to change an input from string to int, then I use hexconvert, to change that into a hex and store it as a string.

Everything seems to work just fine but then for some reason, when I pass it 4096, it gives me back 4096. I was expecting 1000 but I am not sure why it is erroring out on me. I give it 4096 and I notice that it returns an int of 16534, then the program sends that over to the hexconvert and it returns 4096, which, technically is right, but not what I wanted.

It seems to handle other numbers just fine. What am I doing wrong here?

2

There are 2 best solutions below

0
On BEST ANSWER

I think you got an logic error there. If you write:

int n = numconvert("4096");
std::string s = hexconvert(n);

you basically tell it to interpret "4096" already as hex number because you got converter >> hex >> value; inside numconvert, translating it back to hex would always lead to the same getting returned.

What you want is probably

int n = std::stoi("4096");
std::string s = hexconvert(n);

This will interpret "4096" as a normal base 10 number and then convert that to a hex string again using your hexconvert.


That said your numconvert can be written shorter and probably a bit more efficient using std::stoi too, it's basically just:

int numconvert(const std::string& str)
{
    return std::stoi(str, nullptr, 16);
}

we don't need the second argument so we pass nullptr, the 3rd argument is the base.

0
On

Try using the str member instead of the extract operator, to eject the string from the stringstream. Besides being more direct, you don't have to worry about how the extractor further interprets things.