简体   繁体   中英

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM