字节转换问题

字节转换,并分享给大家。

std::string ws2s(const std::wstring& ws)
{
    std::string curLocale = setlocale(LC_ALL, NULL);
    setlocale(LC_ALL, "chs");
    const wchar_t* _Source = ws.c_str();
    size_t _Dsize = 2 * ws.size() + 1;
    char *_Dest = new char[_Dsize];
    memset(_Dest,0,_Dsize);
    wcstombs(_Dest,_Source,_Dsize);
    std::string result = _Dest;
    delete []_Dest;
    setlocale(LC_ALL, curLocale.c_str());
    return result;
}


std::wstring s2ws(const std::string& s)
{
    setlocale(LC_ALL, "chs"); 
    const char* _Source = s.c_str();
    size_t _Dsize = s.size() + 1;
    wchar_t *_Dest = new wchar_t[_Dsize];
    wmemset(_Dest, 0, _Dsize);
    mbstowcs(_Dest,_Source,_Dsize);
    std::wstring result = _Dest;
    delete []_Dest;
    setlocale(LC_ALL, "C");
    return result;
}

注意:wchar_t类型是属于宽字节类型,因此根据char类型的长度去申请内存时,不需要*2。

通过ATL宏定义的方式转换

#include <atlbase.h>
#include <atlconv.h>

USES_CONVERSION;

WCHAR *P =  A2W("12345678");

CHAR *P = W2A(L"12345678");

猜你喜欢

转载自blog.csdn.net/struborn_b/article/details/105920618