将Cstring转换为BYTE [英] conversion of Cstring to BYTE

查看:955
本文介绍了将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类型是 _ 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)
{
    ////
}

一般建议:始终喜欢使用与您的字符编码(即CStringACStringW)匹配的具体CStringT专业名称.该代码将更易于阅读和说明,当您遇到需要帮助的问题时,可以在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天全站免登陆