当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Convert ATL::CString to std::vector<unsigned char>

问题描述:

Here is a function.

inline void Str2Data(std::vector<unsigned char> &To, const CString &From)

{

To.resize(From.GetLength() * sizeof(TCHAR) );

if (!From.IsEmpty())

memcpy(&To[0], From.GetString(), To.size());

}

It converts ok, but if From = "123", To = { '1', '0', '2', '0', '3'}.

Why is it so?

网友答案:

It's likely that TCHAR on your platform is wchar_t, so is two bytes, so CString is really a container of wide chars. What you want is to do a conversion instead of a byte-wise copy:

inline void Str2Data(std::vector<unsigned char> &To, const CString &From)
{
    if (!From.IsEmpty()) {
        To.resize(From.GetLength());
        std::transform(From.GetString(), 
                       From.GetString() + From.GetLength(),
                       To.begin(),
                       [](TCHAR c) { return static_cast<unsigned char>(c); });
    }
    else {
        To.clear();
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: