Fastest way to Convert String to Binary?

前端 未结 3 1734
一整个雨季
一整个雨季 2020-12-01 04:40

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 c

相关标签:
3条回答
  • 2020-12-01 05:07

    Using std::bitset would work:

    #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
    
    0 讨论(0)
  • 2020-12-01 05:09

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

    0 讨论(0)
  • 2020-12-01 05:10

    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!
    
    0 讨论(0)
提交回复
热议问题