8

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;
        ~~~~~~~~~~^~~~~~~~~~
David G
  • 94,763
  • 41
  • 167
  • 253
Felipe
  • 7,013
  • 8
  • 44
  • 102

2 Answers2

8

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
jdehesa
  • 58,456
  • 7
  • 77
  • 121
1

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.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
  • 1
    That's weird, `byte` should have the same size as `char`, no matter how many bits it contains. – llllllllll Oct 08 '18 at 09:46
  • 2
    @liliscent `float`s generally have the same size as `int`s (32 bits), doesn't mean that it's OK to do bit-by-bit copy on a simple assignment. – Dan M. Oct 08 '18 at 10:00
  • 2
    @DanM. You missed my point. My comment was to say the explanation in the answer, especially the mentioning of 8-bits, doesn't justify the non-existence of assignment from `char` to `byte`. IMO, that assignment operator *should* be defined. – llllllllll Oct 08 '18 at 10:04
  • 6
    @liliscent it seems like you are missing the point. `std::byte` is not a character type and is not an arithmetic type. It's made specifically to represent memory bits. Having arbitrary implicit conversions would break it purpose and demote it to just being a typedef for unsigned char, which it is not. – Dan M. Oct 08 '18 at 10:12