码迷,mamicode.com
首页 > 其他好文 > 详细

VS2015 下 unicode 字符转换类

时间:2016-07-08 21:39:54      阅读:835      评论:0      收藏:0      [点我收藏+]

标签:

#include "cutil.h"
#include <Windows.h>
wstring CUtil::UTF8ToUnicode(const string& str)
{
    int  len = 0;
    len = str.length();
    int  unicodeLen = ::MultiByteToWideChar(CP_UTF8,
        0,
        str.c_str(),
        -1,
        NULL,
        0);
    wchar_t *  pUnicode;
    pUnicode = new  wchar_t[unicodeLen + 1];
    memset(pUnicode, 0, (unicodeLen + 1)*sizeof(wchar_t));
    ::MultiByteToWideChar(CP_UTF8,
        0,
        str.c_str(),
        -1,
        (LPWSTR)pUnicode,
        unicodeLen);
    wstring  rt;
    rt = (wchar_t*)pUnicode;
    delete  pUnicode;

    return  rt;
}

string CUtil::UnicodeToUTF8(const wstring& str)
{
    char*     pElementText;
    int    iTextLen;
    // wide char to multi char
    iTextLen = WideCharToMultiByte(CP_UTF8,
        0,
        str.c_str(),
        -1,
        NULL,
        0,
        NULL,
        NULL);
    pElementText = new char[iTextLen + 1];
    memset((void*)pElementText, 0, sizeof(char) * (iTextLen + 1));
    ::WideCharToMultiByte(CP_UTF8,
        0,
        str.c_str(),
        -1,
        pElementText,
        iTextLen,
        NULL,
        NULL);
    string strText;
    strText = pElementText;
    delete[] pElementText;
    return strText;
}

wstring CUtil::ANSIToUnicode(const string& str)
{
    int len = 0;
    len = str.length();
    int unicodeLen = ::MultiByteToWideChar(CP_ACP,
        0,
        str.c_str(),
        -1,
        NULL,
        0);
    wchar_t * pUnicode;
    pUnicode = new wchar_t[unicodeLen + 1];
    memset(pUnicode, 0, (unicodeLen + 1)*sizeof(wchar_t));
    ::MultiByteToWideChar(CP_ACP,
        0,
        str.c_str(),
        -1,
        (LPWSTR)pUnicode,
        unicodeLen);
    wstring rt;
    rt = (wchar_t*)pUnicode;
    delete pUnicode;
    return rt;
}


string CUtil::UnicodeToANSI(const wstring& str)
{
    char*     pElementText;
    int    iTextLen;
    // wide char to multi char
    iTextLen = WideCharToMultiByte(CP_ACP,
        0,
        str.c_str(),
        -1,
        NULL,
        0,
        NULL,
        NULL);
    pElementText = new char[iTextLen + 1];
    memset((void*)pElementText, 0, sizeof(char) * (iTextLen + 1));
    ::WideCharToMultiByte(CP_ACP,
        0,
        str.c_str(),
        -1,
        pElementText,
        iTextLen,
        NULL,
        NULL);
    string strText;
    strText = pElementText;
    delete[] pElementText;
    return strText;
}

 

VS2015 下 unicode 字符转换类

标签:

原文地址:http://www.cnblogs.com/lobsterIT/p/5654411.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!