2016-12-29 56 views
0

我的目標是得到這樣的:的std :: string爲byte []

BYTE  Data1[]  = {0x6b,0x65,0x79}; 
BYTE  Data2[]  = {0x6D,0x65,0x73,0x73,0x61,0x67,0x65}; 

但我的出發點是:

std::string msg = "message"; 
std::string key = "key"; 

我無法擺脫std::stringBYTE[]

我試過如下:

std::vector<BYTE> msgbytebuffer(msg.begin(), msg.end()); 
BYTE*  Data1  = &msgbytebuffer[0]; 

這並沒有引起編譯或運行時錯誤。然而,最終的結果(我把它提供給winapi函數 - crypto api)與我使用最頂級的實際字節數組({0x6D,0x65,0x73,0x73,0x61,0x67,0x65})不一樣。

+1

怎麼樣'的std :: string :: c_str()''返回爲const char *' ? – Quest

+0

感謝Quest提出的建議,我對編寫C++非常新,可否請給我一個片段/演示。 – Noitidart

+1

它以何種方式與衆不同? – Yakk

回答

2

可以使用string::c_str()函數返回一個指針,它可以傳遞給WINAPI像函數C風格的字符串:

foo(string.c_str()); 

其實際作用是,它返回一個指向包含空數組終止字符序列。


我想BYTE []實際上是一個char數組。您可以將您的std :: string從做字符數組:

std::string str = "hello"; 
BYTE byte[6]; // null terminated string; 
strcpy(byte, str.c_str()); // copy from str to byte[] 

如果你要複製的STR無0結尾,使用strncpy代替:

BYTE byte[5]; 
strncpy(byte, str.c_str(), str.length()); 
+0

啊,謝謝Quest,但我需要將它設置爲BYTE [],因爲我在多個地方使用它。但投票給你的時間! – Noitidart

+1

@Noitidart我已經更新了我的答案。 – Quest

+0

啊謝謝你的更新!可否請您展示如何在沒有字符串空終止符的情況下得到它。不好意思,我是個極端新手。 – Noitidart

1

看來我WINAPI正在等待空終止的c字符串。您可以通過使用做到這一點:

msg.c_str(); 

,或者使用​​類型,這樣的事情:

std::vector<BYTE> msgbytebuffer(msg.length() + 1, 0); 
std::copy(msg.begin(), msg.end(), msgbytebuffer.begin()); 
相關問題