简体   繁体   English

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

[英]C++ convert std::string that contains binary data to char*

Okay, so I'm having a little bit of a problem here. 好吧,所以我在这里有点问题。

What I'm doing is converting a binary file (in this example I used a .exe file) to a Base64 string and then converting this one back to binary data to write it to the disk. 我正在做的是将二进制文件(在本示例中使用.exe文件)转换为Base64字符串,然后将其转换回二进制数据以将其写入磁盘。

So far so good, this code works: 到目前为止,此代码有效:

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();

The file "file.exe" is being created as expected and I can run it. 正在按预期创建文件“ file.exe”,我可以运行它。

Now my problem is that I need the decrypted file as char* instead of std::string, but whenever I call this code 现在我的问题是我需要解密的文件为char *而不是std :: string,但是每当我调用此代码时

str.c_str();

to either convert it to const char* or char* the contents suddenly no longer equal the binary data contained in str , but rather this: 将其转换为const char *或char *的内容突然不再等于str中包含的二进制数据,而是这样:

MZP

So, for instance the following code 因此,例如以下代码

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();

would create file.exe, but this time it would contain "MZP" instead of the actual binary data 将创建file.exe,但这次它将包含“ MZP”而不是实际的二进制数据

I have no clue on how to fix this. 我不知道如何解决此问题。 Of course the char* is mandatory. 当然,char *是强制性的。

Can any of you help? 你们有什么可以帮助的吗?

std::string::c_str() returns a "C string", which is a NUL-terminated array of characters. std::string::c_str()返回“ C字符串”,它是NUL终止的字符数组。 Your binary data certainly has NUL terminators in it, prior to the end of the data. 在数据结束之前,您的二进制数据中肯定包含NUL终止符。 This is why your data appears truncated. 这就是为什么您的数据被截断的原因。 (Look in a hex editor, I bet byte 0x03 is zero.) (看一个十六进制编辑器,我打赌字节0x03为零。)

For that reason, you should instead use std::basic_string::data to get a pointer to the raw data contained by the string. 因此,您应该改用std::basic_string::data获取指向该字符串包含的原始数据的指针。 When copying or writing this data, you'll want to not use strcpy (which stops at a NUL byte), but rather memcpy , or similar. 复制或写入此数据时,您不希望使用strcpy (以NUL字节停止),而是使用memcpy或类似方法。 The size of the data contained by the string can be gotten from std::basic_string::size . 字符串包含的数据大小可以从std::basic_string::size

If you want the data inside a std::string as a char* , you can just grab it. 如果您希望将std::string的数据作为char* ,则可以将其获取。 Either: 要么:

std::string s = ...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM