Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/163.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;将包含二进制数据的std::字符串转换为字符*_C++_String_Base64 - Fatal编程技术网

C++ C++;将包含二进制数据的std::字符串转换为字符*

C++ C++;将包含二进制数据的std::字符串转换为字符*,c++,string,base64,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)

好吧,我这里有点小问题

我正在做的是将一个二进制文件(在本例中,我使用了一个.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();
要将其转换为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();
std::string str=base64_解码(base64str);
std::ofstream strm(“file.exe”,std::ios::binary);
char*cstr=新字符[str.length()-1];
strcpy(cstr,str.c_str());

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

std::string s = ...

char* c1 = &s[0];
char* c2 = const_cast<char*>(s.c_str());
char* c3 = &s.front();
std::string s=。。。
char*c1=&s[0];
char*c2=const_cast(s.c_str());
char*c3=&s.front();
std::string::c_str()
返回一个“c字符串”,它是以NUL结尾的字符数组。在数据结束之前,二进制数据中肯定有NUL终止符。这就是数据被截断的原因。(在十六进制编辑器中,我打赌字节0x03为零。)


因此,您应该改为使用获取指向字符串包含的原始数据的指针。复制或写入此数据时,您不希望使用strcpy(在NUL字节处停止),而希望使用memcpy或类似方法。字符串包含的数据大小可以从以下位置获取。

strcpy(cstr,str.c_str())
将在命中第一个空字节(二进制文件中可能有数百个)后停止复制。不要使用
strm好的,我现在有
std::basic_string dec=base64_decode(base64str);char*cdec=新字符[dec.size()];memcpy(cdec,dec.data(),dec.size())尽管如此,它仍然输出“MZP”:/注意:我刚刚测试过它,dec.data()似乎也输出“MZP”注意2:dec.data()在更改
stm
cdec
后似乎工作正常
sizeof(char*)
为4。使用
dec.size()
代替
sizeof(cdec)
std::string s = ...

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