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.

Download  Run Code

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.

Download  Run Code

Output:

67 43 43

 
The behavior of this function is effectively equivalent to:

Download  Run Code

Output:

67 43 43

That’s all about converting string to byte array in C++.