簡體   English   中英

C ++將包含二進制數據的std :: string轉換為char *

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

好吧,所以我在這里有點問題。

我正在做的是將二進制文件(在本示例中使用.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

如果您希望將std::string的數據作為char* ,則可以將其獲取。 要么:

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