This post will discuss how to convert a string to binary in C++.

The std::bitset container is used to store bits in C++. The idea is to iterate over the string and construct a bitset object with the bit values of each character. It can be used as follows to convert string to binary:

Download  Run Code

Output:

01110100 01100101 01100011 01101000

 
Alternatively, we can use a range-based for-loop to iterate over the string.

Download  Run Code

Output:

01110100 01100101 01100011 01101000

 
We can create a utility method to construct a new string, as shown below:

Download  Run Code

Output:

01110100 01100101 01100011 01101000

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