将带有转义字符的大字符串转换为字节数组

时间:2016-06-01 14:28:26

标签: c++ escaping converter

作为一个例子,我有一个以格式

表示为字符串的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 ++)可以做到这一点,或者我必须自己编写:)不想重新发明轮子,我确信之前一定要问过(虽然我找不到)

2 个答案:

答案 0 :(得分:0)

只需使用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() );

答案 1 :(得分:0)

正如我已经理解了你的问题,你希望字符串转换为其代码页等价物的字节数组。这是你可以这样做的方式:

#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