This post will discuss how to get bytes from a string in C++.

1. Using std::transform

Since C++11, we can use std::byte to represent the actual byte data. We can use the std::transform function to transform a string into a vector of bytes:

Download  Run Code

Output:

72 101 108 108 111 44 32 87 111 114 108 100

 
We can even write custom logic for transforming a string to a vector of bytes using a range-based for loop. Here’s what the code would look like:

Download  Run Code

Output:

72 101 108 108 111 44 32 87 111 114 108 100

2. Using c_str() function

A simple solution to get bytes from a string is using the c_str() function that returns read-only const char*.

Download  Run Code

 
To get non-const memory having the write access, we can pass the const char* returned by c_str() to the strcpy() function and get a pointer to the char array. To get a char array instead, we can copy the data to bytes using the std::copy standard copy algorithm:

Download  Run Code

 
To convert a string into a vector of bytes, we can use the range constructor of vector:

Download  Run Code

That’s all about getting bytes from a string in C++.