[C + +] Converts a sequence of bytes into a hexadecimal string

Source: Internet
Author: User

[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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.