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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10184178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:43:44  来源:igfitidea点击:

Fastest way to Convert String to Binary?

c++stringbinarytype-conversion

提问by Derp

I want to convert a string, using the string class - to Binary. What is the fast way to do this character by character. Loop? Or is there some function out there that will convert for me? 1's and 0's binary.

我想使用字符串类将字符串转换为二进制。逐个字符执行此操作的快速方法是什么。环形?或者是否有一些功能可以为我转换?1 和 0 的二进制。

A string being:

一个字符串是:

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

回答by Jesse Good

Using std::bitsetwould work:

使用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;
  }
}

Output:

输出:

01001000
01100101
01101100
01101100
01101111
00100000
01010111
01101111
01110010
01101100
01100100

回答by Mirolimjon Majidov

Try using this with method. Example:

尝试将其与方法一起使用。例子:

#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;
}

result code:

结果代码:

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

回答by Bawantha

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

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