This post will discuss how to convert a string to a vector of bytes in C++.

Starting with C++17, we can use std::byte which represents actual byte data in C++. It is defined in the header <cstddef>. We can convert a single character c to a byte value (collection of bits) with std::byte(c). To convert an entire string to a vector of bytes using any of the following alternatives:

1. Using std::transform

The std::transform standard algorithm applies an operation to each of the elements in the specified range and stores the result in another range. It defined in the <algorithm> header. It can be used as follows to convert a std::string to a std::vector<std::byte>:

Download  Run Code

Output:

67 43 43

2. Using Loop

The idea is to convert each character of the given string to std::byte, and use the push_back() function to append the resultant byte to the end of a vector. This can be done using a range-based for-loop, as shown below:

Download  Run Code

Output:

67 43 43

That’s all about converting a string to a vector of bytes in C++.