将字符串转换为二进制的最快方法?

时间:2012-04-17 02:09:55

标签: c++ string binary type-conversion

我想使用字符串类将字符串转换为Binary。按角色完成这个角色的快捷方法是什么?环?或者是否有一些功能会转换为我? 1和0的二进制。

一个字符串:

#include <string>
using namespace std;
int main(){
  myString = "Hello World";
}

3 个答案:

答案 0 :(得分:33)

使用std::bitset可行:

#include <string>
#include <bitset>
#include <iostream>
using namespace std;
int main(){
  string myString = "Hello World";
  for (std::size_t i = 0; i < myString.size(); ++i)
  {
      cout << bitset<8>(myString.c_str()[i]) << endl;
  }
}

输出:

01001000
01100101
01101100
01101100
01101111
00100000
01010111
01101111
01110010
01101100
01100100

答案 1 :(得分:0)

尝试将其与方法配合使用。示例:

#include <iostream>
#include <bitset>
using namespace std;

string TextToBinaryString(string words) {
    string binaryString = "";
    for (char& _char : words) {
        binaryString +=bitset<8>(_char).to_string();
    }
    return binaryString;
}
int main()
{
    string testText = "Hello World";
    cout << "Test text: " << testText << "!\n";
    cout << "Convert text to binary: " << TextToBinaryString(testText) << "!\n";

    return 0;
}

结果代码:

Test text: Hello World!                                                                                                                                                                                 
Convert text to binary: 0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100!

答案 2 :(得分:0)

char * buf = data.c_str; //buf is binary