Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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";
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
460 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...