20

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";
}
Derp
  • 921
  • 3
  • 14
  • 22

3 Answers3

45

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
Jesse Good
  • 50,901
  • 14
  • 124
  • 166
  • 18
    Or just `bitset<8>(myString[i])` – Jesse Good Apr 17 '12 at 02:37
  • 2
    so bitset<8> would give you base-256, if you want say base-255 or base-257 just add -1 and +1? – pyCthon Jan 02 '13 at 19:34
  • 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? – user899714 Nov 05 '13 at 21:01
  • Add some context by explaining how your answer solves the problem in question, instead of posting a code-only answer. – veeloth Jan 18 '23 at 17:53
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!
0

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

Bawantha
  • 3,644
  • 4
  • 24
  • 36