c++byte

How to convert std::string to std::vector<std::byte> in C++17?


How do I convert a std::string to a std::vector<std::byte> in C++17?

I am filling an asynchronous buffer due to retrieving data as much as possible. So, I am using std::vector<std::byte> on my buffer and I want to convert string to fill it:

std::string gpsValue;
gpsValue = "time[.........";
std::vector<std::byte> gpsValueArray(gpsValue.size() + 1);
std::copy(gpsValue.begin(), gpsValue.end(), gpsValueArray.begin());

...but I am getting this error:

error: cannot convert ‘char’ to ‘std::byte’ in assignment
        *__result = *__first;
        ~~~~~~~~~~^~~~~~~~~~

Solution

  • Using std::transform should work:

    #include <algorithm>
    #include <cstddef>
    #include <iostream>
    #include <vector>
    
    int main()
    {
        std::string gpsValue;
        gpsValue = "time[.........";
        std::vector<std::byte> gpsValueArray(gpsValue.size() + 1);
        std::transform(gpsValue.begin(), gpsValue.end(), gpsValueArray.begin(),
                       [] (char c) { return std::byte(c); });
        for (std::byte b : gpsValueArray)
        {
            std::cout << int(b) << std::endl;
        }
        return 0;
    }
    

    Output:

    116
    105
    109
    101
    91
    46
    46
    46
    46
    46
    46
    46
    46
    46
    0