Convert string to byte array in C++
This post will discuss how to convert string to byte array in C++.
Starting with C++11, we can use std::byte to represent the actual byte data. This post provides an overview of a few plausible options to convert a std::string to a std::byte array.
1. Using std::memcpy
A common solution to perform a binary copy of an array using the std::memcpy function. It can be used to convert a string to a byte array along with the std::string::data function, which returns a pointer to an array containing the C-string representation of the string object.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <cstddef> #include <cstring> int main() { std::string s = "C++"; std::byte bytes[s.length()]; std::memcpy(bytes, s.data(), s.length()); for (auto &b: bytes) { std::cout << std::to_integer<int>(b) << ' '; } return 0; } |
Output:
67 43 43
2. Using std::transform
Another alternative is to use the std::transform function, which applies a given operation to each of the given range elements and stores the result in another range. This is demonstrated below, using the std::byte constructor.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <cstddef> #include <algorithm> #include <vector> int main() { std::string s = "C++"; std::array<std::byte, 3> bytes; std::transform(std::begin(s), std::end(s), std::begin(bytes), [](char c) { return std::byte(c); }); for (auto &b: bytes) { std::cout << std::to_integer<int>(b) << ' '; } return 0; } |
Output:
67 43 43
The behavior of this function is effectively equivalent to:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <cstddef> #include <cstring> #include <algorithm> int main() { std::string s = "C++"; std::byte bytes[s.size()]; for (size_t i = 0; i < s.size(); i++) { bytes[i] = std::byte(s[i]); } for (auto &b: bytes) { std::cout << std::to_integer<int>(b) << ' '; } return 0; } |
Output:
67 43 43
That’s all about converting string to byte array 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 :)