Convert string to binary in C++
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> #include <string> #include <bitset> int main() { std::string str = "tech"; for (std::size_t i = 0; i < str.size(); i++) { std::cout << std::bitset<8>(str[i]) << ' '; } return 0; } |
Output:
01110100 01100101 01100011 01101000
Alternatively, we can use a range-based for-loop to iterate over the string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> #include <string> #include <bitset> int main() { std::string str = "tech"; for (char const &c: str) { std::cout << std::bitset<8>(c) << ' '; } return 0; } |
Output:
01110100 01100101 01100011 01101000
We can create a utility method to construct a new string, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> #include <string> #include <bitset> std::string toBinary(std::string const &str) { std::string binary = ""; for (char const &c: str) { binary += std::bitset<8>(c).to_string() + ' '; } return binary; } int main() { std::string str = "tech"; std::string binary = toBinary(str); std::cout << binary << std::endl; return 0; } |
Output:
01110100 01100101 01100011 01101000
That’s all about converting string to binary 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 :)