1

I need to convert a string into a string with the binary code of the first string. For the first part i used this: Fastest way to Convert String to Binary? Worked perfectly but i can't figure out a way to write it into a new string.

Here's the code i'm using so far:

for (size_t i = 0; i < outputInformations.size(); ++i)
{
    cout << bitset<8>(outputInformations.c_str()[i]);
}

Output:

01110100011001010111001101110100011101010111001101100101011100100110111001100001011011010110010100001010011101000110010101110011011101000111000001100001011100110111001101110111011011110111001001100100

Is there a way to write this into a new string? So that i have a string called "binary_outputInformations" with the binary code inside it.

1

2 Answers 2

2

Are you looking for this ?

  string myString = "Hello World";
  std::string binary_outputInformations;
  for (std::size_t i = 0; i < myString.size(); ++i)
  {
  bitset<8> b(myString.c_str()[i]);
      binary_outputInformations+= b.to_string();
  }

  std::cout<<binary_outputInformations;

Output :

0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100

Sign up to request clarification or add additional context in comments.

Comments

1

Use std::ostringstream (and hopefully C++11):

#include <iostream>
#include <sstream>
#include <bitset>

std::string to_binary(const std::string& input)
{
    std::ostringstream oss;
    for(auto c : input) {
        oss << std::bitset<8>(c);
    }
    return oss.str();
}

int main()
{
    std::string outputInformations("testusername\ntestpassword");
    std::string binary_outputInformations(to_binary(outputInformations));
    std::cout << binary_outputInformations << std::endl;
}

Output:

01110100011001010111001101110100011101010111001101100101011100100110111001100001011011010110010100001010011101000110010101110011011101000111000001100001011100110111001101110111011011110111001001100100

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.