C++で文字列をバイナリに変換する
この投稿では、C++で文字列をバイナリに変換する方法について説明します。
The std::bitset
コンテナは、C++でビットを格納するために使用されます。文字列を反復処理し、各文字のビット値を使用してビットセットオブジェクトを作成するという考え方です。文字列をバイナリに変換するには、次のように使用できます。
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; } |
出力:
01110100 01100101 01100011 01101000
または、範囲ベースのforループを使用して、文字列を反復処理することもできます。
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; } |
出力:
01110100 01100101 01100011 01101000
以下に示すように、新しい文字列を作成するためのユーティリティメソッドを作成できます。
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; } |
出力:
01110100 01100101 01100011 01101000
これで、C++で文字列をバイナリに変換できます。
こちらも参照: