Convert a string to a vector of bytes in C++
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>:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#include <iostream> #include <vector> #include <algorithm> #include <cstddef> using namespace std; std::vector<std::byte> getBytes(std::string const &s) { std::vector<std::byte> bytes; bytes.reserve(s.size()); std::transform(std::begin(s), std::end(s), std::back_inserter(bytes), [](char c){ return std::byte(c); }); return bytes; } int main() { std::string s = "C++"; std::vector<std::byte> bytes = getBytes(s); for (auto &b: bytes) { std::cout << std::to_integer<int>(b) << ' '; } return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <iostream> #include <vector> #include <algorithm> #include <cstddef> using namespace std; std::vector<std::byte> to_bytes(std::string const &s) { std::vector<std::byte> bytes; for (char c: s) { bytes.push_back(std::byte(c)); } return bytes; } int main() { std::string s = "C++"; std::vector<std::byte> bytes = to_bytes(s); for (auto &b: bytes) { std::cout << std::to_integer<int>(b) << ' '; } return 0; } |
Output:
67 43 43
That’s all about converting a string to a vector of bytes in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)