【问题标题】:Convert a string of binary into an ASCII string (C++)将二进制字符串转换为 ASCII 字符串 (C++)
【发布时间】:2014-06-14 04:28:39
【问题描述】:

我有一个包含 32 位二进制的字符串变量。将二进制表示的这 4 个字符(8 位是一个字符)转换回它们的 ASCII 字符的最佳方法是什么?

例如,变量包含“01110100011001010111001101110100”,应将其转换回字符串“test”。

【问题讨论】:

  • 人们只能想知道您最终是如何将 ASCII 编码的文本存储为字符的文本二进制表示。也许从根本上解决问题会更有成效。
  • 查看std::bitset
  • 只是猜测——这听起来像是家庭作业,<humor> 攻击教授在</humor> 上是不受欢迎的
  • @DavidHeffernan 你说得很对,我对 C++ 还很陌生,只是发现了 std::bitset。我知道我的方法确实感觉很不对劲!

标签: c++ binary ascii


【解决方案1】:

如果您使用的是 C++11,则另一种选择:

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

int main()
{
    std::string data = "01110100011001010111001101110100";
    std::stringstream sstream(data);
    std::string output;
    while(sstream.good())
    {
        std::bitset<8> bits;
        sstream >> bits;
        char c = char(bits.to_ulong());
        output += c;
    }

    std::cout << output;

   return 0;
}

请注意,bitset 是 C++11 的一部分。

还要注意,如果数据格式不正确,当 sstream.good() 返回 false 时,结果将被静默截断。

【讨论】:

  • 谢谢,这个解决方案有效,我刚刚发现了 std::bitset,所以我会研究一个更优雅的解决方案。
【解决方案2】:

尝试使用 this with 方法。示例:

#include <iostream>
#include <bitset>
#include <sstream>
using namespace std;

string BinaryStringToText(string binaryString) {
    string text = "";
    stringstream sstream(binaryString);
    while (sstream.good())
    {
        bitset<8> bits;
        sstream >> bits;
        text += char(bits.to_ulong());
    }
    return text;
}

int main()
{
    string binaryString = "0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100";
    cout << "Binary string: " << binaryString << "!\n";
    cout << "Result binary string to text: " << BinaryStringToText(binaryString) << "!\n";

    return 0;
}

结果代码:

Binary string: 0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100!                                                                                                  
Result binary string to text: Hello World! 

【讨论】:

    【解决方案3】:
    #include <iostream>
    #include <vector>
    #include <bitset>
    
    using namespace std;  
    
    int main()
    try
    {
    
       string myString = "Hello World"; // string object
    
       vector<bitset<8>> us;           // string to binary array of each characater
    
       for (int i = 0; i < myString.size(); ++i)
       {
            // After convert string to binary, push back of the array
            us.push_back(bitset<8>(myString[i]));
       }
    
       string c;  // binary to string object
    
       for (int i = 0; i < us.size(); ++i)
        {
            // the function 'to_ulong' returns
            // integer value with the same bit representation as the bitset object.
            c += char(us[i].to_ulong());
        }
    
        cout << c;
    
    }
    catch (exception& e)
    {
        cerr << "the error is : " << e.what() << '\n';
    }
    

    输出:Hello World

    Fastest way to Convert String to Binary?

    要将字符串转换为二进制,我参考了上面链接的答案。

    Convert a string of binary into an ASCII string (C++)

    要将二进制转换为字符串,我参考了上面链接的答案,Dale Wilson 的答案。

    【讨论】:

      【解决方案4】:

      这是我的尝试:

      std::string str2bits(const std::string_view &str, bool big_endian = false)
      {
          std::string ret;
          ret.reserve(str.size() * 8);
          for (size_t i = 0; i < str.length(); ++i)
          {
              const uint8_t ord = uint8_t(str[i]);
              for (int bitnum = (big_endian ? 0 : 7);; (big_endian ? (++bitnum) : (--bitnum)))
              {
                  if ((big_endian && bitnum >= 8) || (!big_endian && bitnum < 0))
                  {
                      break;
                  }
                  if (ord & (1 << bitnum))
                  {
                      ret += "1";
                  }
                  else
                  {
                      ret += "0";
                  }
              }
          }
          return ret;
      }
      

      str2bits("test") ==> 01110100011001010111001101110100

      【讨论】:

        【解决方案5】:

        另一种方法可能是这样,更灵活:

        #include <iostream>
        #include <string>
        #include <math.h>
        
        std::string BinaryTextToASCIIText(const std::string& binaryText, const unsigned int blockSize = 8, const unsigned int separatorLength = 1)
        {
            std::string text(""), block;
            unsigned int separatorBlockStartIndex = blockSize;
        
            for (unsigned int i = 0; i < binaryText.length(); i++)
            {
                if (i == separatorBlockStartIndex)
                {
                    i += separatorLength;
                    separatorBlockStartIndex += blockSize + separatorLength;
                }
                
                block += binaryText[i];
        
                if (block.length() == 8)
                {
                    char binaryTextToASCIIChar = 0;
                    for (unsigned int j = 0; j < block.length(); j++)
                    {
                        if (block[j] == '1')
                        {
                            binaryTextToASCIIChar += pow(2, block.length() - j - 1);
                        }
                    }
        
                    block.clear();
                    text += binaryTextToASCIIChar;
                }
            }
        
            return text;
        }
        
        int main()
        {
            //if you have your binary text in blocks of 32 bits and the blocks have been separated with " " (the separator can be any kind of ascii character and any length) you can use the function like this:
            std::cout << BinaryTextToASCIIText("01110100011001010111001101110100", 32, 1) << std::endl;
            //here is an example of blocks of 32 bits and the "0101111011010" (13 characters long) separator
            std::cout << BinaryTextToASCIIText("010101000110100001101001011100110101111011010001000000110100101110011001000000101111011010011000010010000001110100011001010101111011010011100110111010000100001", 32, 13);
        
            return 0;
        }
        

        当然,该方法可以更有用..可以肯定地改进,但效果很好。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-31
          • 2017-02-23
          • 2014-08-03
          • 1970-01-01
          相关资源
          最近更新 更多