[C + +] Converts a sequence of bytes into a hexadecimal string
Rayleahaan@hotmail.com
The first thought is to use the format of the output stream in C + +, string stream to connect a string, exactly what we want. Copying these bytes into the stream with the copy algorithm seems most intuitive:
std::string bytes_to_hexstr (unsigned char*, unsigned, char*)
{
Std::ostringstream OSS;
OSS << Std::hex << std::setw (2) << Std::setfill (' 0 ');
Std::copy (The std::ostream_iterator<int> (OSS));
return Oss.str ();
}
However, the result is wrong because SETW this manipulator is only valid for the next output, so only the first byte conversion is correct. Rewriting a custom ostream_iterator is too expensive, or writing a custom type of output is tedious enough, or using a handwritten loop:
std::string bytes_to_hexstr (unsigned char*, unsigned, char*)
{
Std::ostringstream OSS;
OSS << std::hex << std::setfill (' 0 ');
while (first<last) OSS << STD::SETW (2) << int (*first++);
return Oss.str ();
}
It is important to note that the unsigned char must be converted to an int, since the hex this manipulator is only valid for the output of an integer value.
Last Modified:sunday, April 17th, 2005
HTML Conversion by Tex2page 2005-02-27