luftwaffe
September 11th, 2002, 02:02 PM
Hello,
What is the fastest way to convert a string represents four hex values as a continuous flow (for example char*c = "10FF36CC") to convert to a string contains decimal values [and perhaps separator dots]? 16.255.54.204
?
willchop
September 11th, 2002, 07:54 PM
luftwaffe,
The example I'm providing uses STL strings and streams to get
the job done. The code assumes the input string is comprised
of consecutive hex numbers that are two characters long. I
threw it together quickly as a starting place for you. You can
probably optimize it if you do some profiling.
bool make_decimal_ip_str(const std::string& in_str, std::string& out_str)
{
out_str.erase();
std::string::size_type pos = 0;
while (pos < in_str.size()) {
// Isolate two char hex
std::string hex_str = in_str.substr(pos, 2);
// Extract integer val from hex string
std::istringstream iss(hex_str);
int val = 0;
iss >> std::hex >> val;
if (iss.fail())
return false;
// Insert integer value to string as decimal
std::ostringstream oss;
oss << val;
if (oss.fail())
return false;
// Build result string
out_str += oss.str() + ".";
// Increment substring pos
pos += 2;
}
// Remove last dot
out_str.erase(out_str.end()-1);
return true;
}
int main(int argc, char* argv[])
{
std::string result_str;
std::string input_str = "10FF36CC";
make_decimal_ip_str(input_str, result_str);
std::cout << "hex: " << input_str << " dec: " << result_str << std::endl;
return 0;
}
regards, willchop