Cstring 到 BYTE 的转换 [英] conversion of Cstring to BYTE

查看:77
本文介绍了Cstring 到 BYTE 的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Visual Studio c++ 并希望将 Cstring 转换为 Byte.我已经编写了这段代码,但它在第二行给了我数据"未定义的错误.

I am using Visual Studio c++ and want to convert the Cstring to Byte. I have written this code but it gave me error in the second line that "data" is undefined.

CString data = _T( "OK");
LPBYTE pByte = new BYTE[data.GetLength() + 1];
memcpy(pByte, (VOID*)LPCTSTR(data), data.GetLength());

我还需要将 LPBYTE 转换为 const char 以用于 strcmp 函数.我已经编写了代码,但我找不到它的问题.

Further more I need to convert LPBYTE to const char for strcmp function. I have written the code but I can't find the issue with it.

const LPBYTE lpBuffer;
LPBYTE lpData = lpBuffer;
CString rcvValue(LPCSTR(lpBuffer));
const CHAR* cstr = (LPCSTR)rcvValue;
if (strcmp (cstr,("ABC")) == 0)
{
    ////
}

推荐答案

CString 类型是 CStringT,取决于它使用的字符集(CStringA for ANSI, CStringW 用于 Unicode).虽然使用 _T 宏,您在将受控序列复制到缓冲区时未能考虑不同的大小要求.

The CString type is a template specialization of CStringT, depending on the character set it uses (CStringA for ANSI, CStringW for Unicode). While you ensure to use a matching encoding when constructing from a string literal by using the _T macro, you fail to account for the different size requirements when copying the controlled sequence to the buffer.

以下代码修复了第一部分:

The following code fixes the first part:

CString data = _T("OK");
size_t size_in_bytes = (data.GetLength() + 1) * sizeof(data::XCHAR);
std::vector<BYTE> buffer(size_in_bytes);
unsigned char const* first = static_cast<unsigned char*>(data.GetString());
unsigned char const* last = first + size_in_bytes;
std::copy(first, last, buffer.begin());

第二个问题是真正要求解决已解决的问题.CStringT 类型已经提供了 CStringT::Compare 成员,可以使用:

The second question is really asking to solve a solved problem. The CStringT type already provides a CStringT::Compare member, that can be used:

const LPBYTE lpBuffer;
CString rcvValue(static_cast<char const*>(lpBuffer));
if (rcvValue.Compare(_T("ABC")) == 0)
{
    ////
}

一般建议:始终喜欢使用与您的字符编码匹配的具体 CStringT 特化,即 CStringACStringW.代码将更易于阅读和推理,当您遇到需要帮助的问题时,您可以在 Stack Overflow 上发布问题,而无需解释您使用的编译器设置.

General advice: Always prefer using the concrete CStringT specialization matching your character encoding, i.e. CStringA or CStringW. The code will be much easier to read and reason about, and when you run into problems you need help with, you can post a question at Stack Overflow, without having to explain, what compiler settings you are using.

这篇关于Cstring 到 BYTE 的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆