Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

byte

How do I convert a std::string to a std::vector<std::byte> in C++17? Edited: 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;
        ~~~~~~~~~~^~~~~~~~~~
like image 439
Felipe Avatar asked Oct 08 '18 09:10

Felipe


2 Answers

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
like image 142
jdehesa Avatar answered Sep 19 '22 13:09

jdehesa


std::byte is not supposed to be a general purpose 8-bit integer, it is only supposed to represent a blob of raw binary data. Therefore, it does (rightly) not support assignment from char.

You could use a std::vector<char> instead - but that's basically what std::string is.


If you really want to convert your string to a vector of std::byte instances, consider using std::transform or a range-for loop to perform the conversion.

like image 25
Vittorio Romeo Avatar answered Sep 16 '22 13:09

Vittorio Romeo