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?
I think you got an logic error there. If you write:
you basically tell it to interpret "4096" already as hex number because you got
converter >> hex >> value;
insidenumconvert
, translating it back to hex would always lead to the same getting returned.What you want is probably
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:we don't need the second argument so we pass
nullptr
, the 3rd argument is the base.