【问题标题】:C++ string to binary code / binary code to stringC++字符串到二进制代码/二进制代码到字符串
【发布时间】:2013-09-21 21:36:41
【问题描述】:

我需要用第一个字符串的二进制码将一个字符串转换成一个字符串。 对于第一部分,我使用了这个:Fastest way to Convert String to Binary? 工作得很好,但我不知道如何将它写入新字符串。

这是我目前使用的代码:

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

输出:

01110100011001010111001101110100011101010111001101100101011100100110111001100001011011010110010100001010011101000110010101110011011101000111000001100001011100110111001101110111011011110111001001100100

有没有办法把它写成一个新的字符串?这样我就有了一个名为“binary_outputInformations”的字符串,其中包含二进制代码。

【问题讨论】:

标签: c++ string binary


【解决方案1】:

你在找这个吗?

  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;

输出:

0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100

【讨论】:

    【解决方案2】:

    使用std::ostringstream(希望是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;
    }
    

    输出:

    01110100011001010111001101110100011101010111001101100101011100100110111001100001011011010110010100001010011101000110010101110011011101000111000001100001011100110111001101110111011011110111001001100100
    

    【讨论】:

      最近更新 更多