Reputation: 7563
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;
~~~~~~~~~~^~~~~~~~~~
Upvotes: 8
Views: 8969
Reputation: 59681
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
Upvotes: 8
Reputation: 93264
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.
Upvotes: 1