【问题标题】:C++ convert std::string that contains binary data to char*C++ 将包含二进制数据的 std::string 转换为 char*
【发布时间】:2014-10-31 02:02:23
【问题描述】:

好的,所以我这里有点问题。

我正在做的是将二进制文件(在此示例中我使用 .exe 文件)转换为 Base64 字符串,然后将其转换回二进制数据以将其写入磁盘。

到目前为止一切顺利,这段代码有效:

std::string str = base64_decode(base64str); // base64str is the base64 string made of the actual .exe file
std::ofstream strm("file.exe", std::ios::binary);
strm << str;
strm.close();

文件“file.exe”正在按预期创建,我可以运行它。

现在我的问题是我需要解密文件作为 char* 而不是 std::string,但是每当我调用此代码时

str.c_str();

要将其转换为 const char* 或 char*,内容突然不再等于 str 中包含的二进制数据,而是这样:

MZP

所以,比如下面的代码

std::string str = base64_decode(base64str);
std::ofstream strm("file.exe", std::ios::binary);
char* cstr = new char[str.length()-1];
strcpy(cstr, str.c_str());
strm << cstr;
strm.close();

将创建 file.exe,但这次它将包含“MZP”而不是实际的二进制数据

我不知道如何解决这个问题。当然 char* 是强制性的。

你们可以帮忙吗?

【问题讨论】:

  • strcpy(cstr, str.c_str()); 将在遇到第一个空字节后停止复制,您的二进制文件中可能有数百个空字节。
  • 不要使用strm &lt;&lt; cstr,它将在第一个空值处停止。使用strm.write()

标签: c++ string base64


【解决方案1】:

std::string::c_str() 返回一个“C 字符串”,它是一个以 NUL 结尾的字符数组。在数据结束之前,您的二进制数据中肯定有 NUL 终止符。这就是您的数据出现截断的原因。 (查看十六进制编辑器,我敢打赌字节 0x03 为零。)

因此,您应该改用std::basic_string::data 来获取指向字符串包含的原始数据的指针。复制或写入此数据时,您不希望使用 strcpy(在 NUL 字节处停止),而是使用 memcpy 或类似名称。字符串包含的数据大小可以从std::basic_string::size获取。

【讨论】:

  • 好的,我现在有std::basic_string&lt;char&gt; dec = base64_decode(base64str); char* cdec = new char[dec.size()]; memcpy(cdec, dec.data(), dec.size()); 虽然它仍然输出“MZP”:/
  • 注:我刚刚测试过,dec.data() 似乎也输出“MZP”
  • 注 2:将 stm &lt;&lt; cdec 更改为 strm.write(dec.data(), dec.size()) 后,dec.data() 似乎可以正常工作,但 strm.write(cdec, sizeof(cdec)) 仍然无法正常工作(“MZP”事情)
  • cdecchar*sizeof(char*) 是 4。使用 dec.size() 而不是 sizeof(cdec)
【解决方案2】:

如果您想将std::string 中的数据作为char*,您可以直接抓取它。要么:

std::string s = ...

char* c1 = &s[0];
char* c2 = const_cast<char*>(s.c_str());
char* c3 = &s.front();

【讨论】:

    猜你喜欢
    • 2010-11-14
    • 1970-01-01
    • 2012-09-03
    • 1970-01-01
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 2012-11-04
    相关资源
    最近更新 更多