Vikash
Vikash

Reputation: 77

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

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.

Upvotes: 1

Views: 2098

Answers (1)

Fred Larson
Fred Larson

Reputation: 62053

  • Your uint8_t values are being interpreted as characters. Convert them to integers for stream operations
  • Use std::hex for stream operations to convert integers to hexadecimal representation
  • Add "0x", as std::hex won't do that for you.
  • Add a space after your comma
std::string HexString(std::vector<std::uint8_t> &bytes)
{
    std::stringstream ss;
    for (std::size_t i = 0; i < bytes.size(); i++)
    {
        if (i != 0)
        {
            ss << ", ";
        }
        ss << "0x" << std::hex << static_cast<int>(bytes[i]);
    }
    return ss.str();
}

With that, I get:

Should be equal
0x41, 0x7c, 0xea, 0x9a, 0xaf
0x41, 0x7c, 0xea, 0x9a, 0xaf

Upvotes: 4

Related Questions