Fastest way to Convert String to Binary?

88,763

Solution 1

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

Solution 2

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!
Share:
88,763
Derp
Author by

Derp

Updated on July 05, 2022

Comments

  • Derp
    Derp almost 2 years

    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.

    A string being:

    #include <string>
    using namespace std;
    int main(){
      myString = "Hello World";
    }
    
  • Jesse Good
    Jesse Good about 12 years
    Or just bitset<8>(myString[i])
  • pyCthon
    pyCthon over 11 years
    so bitset<8> would give you base-256, if you want say base-255 or base-257 just add -1 and +1?
  • user899714
    user899714 over 10 years
    if we want to sum the outputs such that if there is an overflow bit (0 or 1) at the end of the sum on MSB side, then that should get added to the final answer of the sum again. how can we do that?
  • Arun Vinoth - MVP
    Arun Vinoth - MVP over 4 years
    Add some context by explaining how your answer solve the problem in question, instead of posting code-only answer.