std ::字符串到字节[]

std::string to BYTE[]

本文关键字:字符串 std 到字节      更新时间:2023-10-16

我的目标是获得:

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})。

您可以使用string::c_str()函数,该功能将指针返回到C样式字符串,该函数可以传递给Winapi函数,例如:

foo(string.c_str());

它实际上要做的是它将指针返回到包含null终止字符序列的数组。


我想字节[]实际上是一个char数组。您可以通过:

将std ::字符串分配给字符阵列
std::string str = "hello";
BYTE byte[6];   // null terminated string;
strcpy(byte, str.c_str());  // copy from str to byte[]

如果要在末端复制不带0的str,请改用strncpy

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

似乎我正在等待一个终止的c弦。您可以通过使用:

来实现这一目标
msg.c_str();

或使用您的BYTE类型,类似的东西:

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