How to convert vector of uint8_t into std::string in C++?

  c++, c++11, c++14

I’m trying to convert the bytes in to string correctly. But the converted string looks like a garbage. I have the following code:

#include <iostream>
#include <sstream>
#include <vector>

 std::string HexString( std::vector<std::uint8_t> &bytes ) {
                std::stringstream ss;
                for ( std::int32_t i = 0; i < bytes.size(); i++ ) {
                    if(i != 0)
                        ss << ",";
                    ss << bytes[i];
                }
                return ss.str();
}

int main() {
    std::vector<uint8_t> uuid = {
                 0x41,0x7c, 0xea, 0x9a,0xaf
    };
    
    std::string uuidString = HexString(uuid);
    
    std::cout << "Should be equal" << std::endl;
    std::cout << uuidString << std::endl;
    std::cout << "0x41, 0x7c, 0xea, 0x9a, 0xaf" << std::endl;

    return 0;
}

Output:

Both should be equal:
A,|,�,�,�
0x41, 0x7c, 0xea, 0x9a, 0xaf

Correct output should be:

Both should be equal:
0x41, 0x7c, 0xea, 0x9a, 0xaf
0x41, 0x7c, 0xea, 0x9a, 0xaf

Any suggestions would be appreciated.

Source: Windows Questions C++

LEAVE A COMMENT