cout << "Hello World!" << endl; // 张鲁夺 :: 个人博客,幸福着你的幸福!


VC++中Unicode,Ansi,Utf-8字符集转换

作者:鲁夺,2015年9月28日,原创文章,转载请注明出处!

原文:http://zhangluduo.com/article/cb11b50f/



//
// UNICODE,MBCS,UTF-8字符集转换
//

static void UnicodeToAnsi(/* _IN */WCHAR* text, /* _OUT */CHAR** out);
static void UnicodeToAnsi_Release(/* _IN */CHAR** out);
static void AnsiToUnicode(/* _IN*/ CHAR* text, /* _OUT */WCHAR** out);
static void AnsiToUnicode_Release(/* _IN */WCHAR** out);

static void UnicodeToUtf8(/* _IN */WCHAR* text, /* _OUT */CHAR** out);
static void UnicodeToUtf8_Release(/* _IN */CHAR** out);
static void Utf8ToUnicode(/* _IN*/ CHAR* text, /* _OUT */WCHAR** out);
static void Utf8ToUnicode_Release(/* _IN */WCHAR** out);

void UnicodeToAnsi(/* _IN */WCHAR* text, /* _OUT */CHAR** out)
{
    *out = NULL;

    int len = WideCharToMultiByte(CP_ACP, 0, text, -1, NULL, NULL, NULL, NULL);
    if (len > 0) 
    {
        CHAR* buffer = new CHAR[len + 1];
        memset(buffer, 0, len + 1);
        WideCharToMultiByte(CP_ACP, 0, text, -1, buffer, len, NULL, NULL);

        *out = buffer;
    }
}

void UnicodeToAnsi_Release(/* _IN */CHAR** out)
{
    if (*out)
    {
        delete (*out);
        (*out) = NULL;
    }
}

void AnsiToUnicode(/* _IN*/ CHAR* text, /* _OUT */WCHAR** out)
{
    *out = NULL;

    int len = MultiByteToWideChar(CP_ACP, 0, text, -1, NULL, NULL);
    if (len > 0)
    {
        WCHAR *buffer = new WCHAR[len + 1];
        memset(buffer, 0, (len + 1 )* sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP, 0, text, -1, buffer, len);

        (*out) = buffer;
    }
}

void AnsiToUnicode_Release(/* _IN */WCHAR** out)
{
    if (*out)
    {
        delete (*out);
        (*out) = NULL;
    }
}

void UnicodeToUtf8(/* _IN */WCHAR* text, /* _OUT */CHAR** out)
{
    *out = NULL;

    int len = WideCharToMultiByte(CP_UTF8, 0, text, -1, NULL, NULL, NULL, NULL);
    if (len > 0) 
    {
        CHAR* buffer = new CHAR[len + 1];
        memset(buffer, 0, len + 1);
        WideCharToMultiByte(CP_UTF8, 0, text, -1, buffer, len, NULL, NULL);

        *out = buffer;
    }
}

void UnicodeToUtf8_Release(/* _IN */CHAR** out)
{
    if (*out)
    {
        delete (*out);
        (*out) = NULL;
    }
}

void Utf8ToUnicode(/* _IN*/ CHAR* text, /* _OUT */WCHAR** out)
{
    *out = NULL;

    int len = MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, NULL);
    if (len > 0)
    {
        WCHAR *buffer = new WCHAR[len + 1];
        memset(buffer, 0, (len + 1 )* sizeof(WCHAR));
        MultiByteToWideChar(CP_UTF8, 0, text, -1, buffer, len);

        (*out) = buffer;
    }
}

void Utf8ToUnicode_Release(/* _IN */WCHAR** out)
{
    if (*out)
    {
        delete (*out);
        (*out) = NULL;
    }
}

Copyright © 2015 Zhang Luduo.

All rights reserved.