To avoid the overflow from @Evan Teran 's answer, I'll just use a wider type, ie size_t
suitable for common use cases.
convert.cpp
#include <iostream>
#include <sstream>
#include <exception>
size_t convertHex(const std::string& hexStr)
{
std::cout << "This trick can print values up to: " << static_cast<size_t>(-1);
std::cout << std::endl;
std::stringstream ssBuff {};
size_t x {0};
ssBuff << std::hex << hexStr;
ssBuff >> x;
if(!ssBuff.eof() || ssBuff.fail())
{
throw std::runtime_error("Conversion in stringstream failed.");
}
return x;
}
int main(int argc, char* argv[])
{
if(2 != argc)
{
std::cout << "Usage: " << argv[0] << " [hex_string_to_convert].";
std::cout << std::endl;
return -1;
}
try
{
std::string hexStr{argv[1]};
size_t value = convertHex(hexStr);
std::cout << hexStr << " = " << value << std::endl;
}
catch(std::runtime_error &e)
{
std::cout << "\tError: " << e.what() << std::endl;
return -1;
}
return 0;
}
g++ -o app convert.cpp && ./app fffefffe
Output:
This trick can print values up to: 18446744073709551615
fffefffe = 4294901758
./app fffefffefffffffffffffffffffffffffffffffff
Output:
This trick can print values up to: 18446744073709551615
Error: Conversion in stringstream failed.