Vector of number to string in hexadecimal format

Viewed 563

I created a vector std::vector<uint8_t> vec{ 0x0C, 0x14, 0x30 };

I want to return the values of the vector in a string "0CD430".

I created this simple code:

std::string vectorTostring(const std::vector<uint8_t>& vec)
{
    std::string result;
    for (const auto& v : vec)
    {
        result += std::to_string(v);
    }
    return result;
}

in this case the result will be "122048". Wow the hex values are stored in the vector of bytes and why I got the decimal value and not the hex value using to_string?

1 Answers

I would suggest using a std::stringstream and some output manipulators like so:

#include <sstream>
#include <iomanip>
#include <vector>
#include <string>
#include <iostream>

std::string vectorTostring(const std::vector<uint8_t>& vec)
{
    std::stringstream result;
    for (const auto& v : vec)
    {
        result 
            << std::setfill('0') << std::setw(sizeof(v) * 2)
            << std::hex << +v;
    }
    return result.str();
}

int main()
{
    std::cout << vectorTostring({ 0x0c, 0x14, 0x30 }) << std::endl;
}

To take it in reverse order:

  • +v promotes the uint8_t/char to int, so that it outputs the value and not the ASCII character.
  • std::hex makes it output in hex format - but 11 becomes B not 0B
  • std::setw(sizeof(v) * 2) sets the output width to double the number of bytes in a v-type - here just 1*2. Now 11 becomes " B".
  • std::setfill('0') sets the fill character to 0, and finally 11 is turned into 0B.
Related