Reputation: 77
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
Reputation: 62053
uint8_t
values are being interpreted as characters. Convert them to integers for stream operationsstd::hex
for stream operations to convert integers to hexadecimal representationstd::hex
won't do that for you.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