C++ 将包含二进制数据的 std::string 转换为 char*

标签 c++ string base64

好的,所以我在这里遇到了一点问题。

我所做的是将一个二进制文件(在本例中我使用的是 .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* 是强制性的。

你们能帮忙吗?

最佳答案

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

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

关于C++ 将包含二进制数据的 std::string 转换为 char*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26666444/

相关文章:

c++ - 概念示例的简单 C++ 接口(interface)

python - 字符串搜索库的结果 - 错误或功能或我的编码错误?

python - 将字符串解析为 boolean 值?

android - 从字符串 Base64 到位图的 Covert 问题

javascript - 在 go 中编码可执行文件并在 javascript 中解码不起作用

python - RFM69 radio 收发器 : Arduino is not registering acknowledgement for transmission sent by Raspberry Pi

c++ - Windows 中的 gethostname()

python - 如何更改字典中的变量

ruby-on-rails - 如何使用 ruby​​ 将 base64 字符串保存为图像

C++11 - move 语义在构造上很慢