【问题标题】:convert a large string with escaped chars to a byte array将带有转义字符的大字符串转换为字节数组
【发布时间】:2016-09-30 23:49:49
【问题描述】:

例如,我有一个 jpeg 表示为格式中的字符串

ÿØÿà\\0\x10JFIF\\0\x01\x01\\0\\0\x01\\0\x01

我想看到这个文件的二进制图像,即带有值的字节数组

FF D8 FF E0 5C 30 10 4A 46 49 46 5C 30 01 01 5C etc.

是否有一些代码(C/C++)可以做到这一点,或者我必须自己编写:) 不想重新发明轮子,我敢肯定这之前一定被问过(虽然我找不到)

【问题讨论】:

  • 引用的十六进制是否应该是结果的开头?字符串的编码是什么?假设单字节ASCII: ÿØÿà\0\x10JFIF\0\x01\x01\0\0\x01\0\x01 实际上解析为 [c3 bf c3 98 c3 bf c3 a0 5c 30 5c 78 31 30 4a 46 49 46 5c 30 5c 78 30 31 5c 78 30 31 5c 30 5c 30 5c 78 30 31 5c 30 5c 78 30 31]

标签: c++ escaping converter


【解决方案1】:

只需使用std::ostream::write() 方法:

char str[] = "ÿØÿà\0\x10JFIF\0\x01\x01\0\0\x01\0\x01";
std::ofstream out( "file", ios::bin | ios::out );
out.write( str, sizeof( str ) - 1 ); // assuming you do not need to store leading \0

// or using std::string
std::string str { "ÿØÿà\0\x10JFIF\0\x01\x01\0\0\x01\0\x01", 19 );
std::ofstream out( "file", ios::bin | ios::out );
out.write( str.data(), str.length() );

【讨论】:

    【解决方案2】:

    据我了解您的问题,您希望将字符串转换为其代码页等效项的字节数组。您可以这样做:

    #include <string>
    #include <sstream>
    #include <iomanip>
    #include <vector>
    
      // You must know the length of your string resp. how many characters it contains.
      // Otherwise it would end at the first \0 character.
      std::string s{ "ÿØÿà\0\x10JFIF\0\x01\x01\0\0\x01\0\x01", 18 };
      std::istringstream ss(s);
    
      std::vector<unsigned char> byteArray;
      for (std::size_t i = 0; !ss.eof() && i < s.size(); ++i) {
       byteArray.emplace_back(ss.get()); // C++98: byteArray.push_back(ss.get());
      }
      for each (auto byte in byteArray)
      {
       // enforce byte to be treated as a number by putting it in a dummy addition expression
       std::cout << std::setfill('0') << std::setw(2) << std::hex << 0 + byte << " "; 
      }
      std::cout << std::endl;
    

    这导致使用 VS2013 的以下输出:

      ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多