Ansi22Utf8.h

#pragma once

#include <string>
#include <vector>
using namespace std;

class Ansi22Utf8
{
public:
Ansi22Utf8(void);
~Ansi22Utf8(void);

private:
wchar_t* AnsiToUnicode(const char* buf);
char* UnicodeToUtf8(const wchar_t* buf);

wchar_t * UTF8ToUnicode( const char* str );
char * UnicodeToANSI( const wchar_t *str );

public:
char* UTF8ToANSI(const char* buf);
char* AnsiToUtf8(const char* buf);
};


Ansi22Utf8.cpp

#include "StdAfx.h"
#include "Ansi22Utf8.h"
#include <Windows.h>

Ansi22Utf8::Ansi22Utf8(void)
{
}


Ansi22Utf8::~Ansi22Utf8(void)
{
}

//UTF8转成Unicode
wchar_t * Ansi22Utf8::UTF8ToUnicode( const char* str )
{
int textlen = 0;
wchar_t * result;
textlen = MultiByteToWideChar( CP_UTF8, 0, str,-1, NULL,0 );
result = (wchar_t *)malloc((textlen+1)*sizeof(wchar_t));
memset(result,0,(textlen+1)*sizeof(wchar_t));
MultiByteToWideChar(CP_UTF8, 0,str,-1,(LPWSTR)result,textlen );
return result;
}

//Unicode转成ANSI
char * Ansi22Utf8::UnicodeToANSI( const wchar_t *str )
{
char * result;
int textlen = 0;
// wide char to multi char
textlen = WideCharToMultiByte( CP_ACP, 0, str, -1, NULL, 0, NULL, NULL );
result =(char *)malloc((textlen+1)*sizeof(char));
memset( result, 0, sizeof(char) * ( textlen + 1 ) );
WideCharToMultiByte( CP_ACP, 0, str, -1, result, textlen, NULL, NULL );
return result;
}

char* Ansi22Utf8::UTF8ToANSI(const char* buf)
{
return UnicodeToANSI(UTF8ToUnicode(buf));
}

//ANSI转成Unicode
wchar_t* Ansi22Utf8::AnsiToUnicode(const char* buf)
{
int textlen = 0;

wchar_t* result;

textlen = MultiByteToWideChar(CP_ACP,0,buf,-1,NULL,0);

result = (wchar_t *)malloc((textlen+1)*sizeof(wchar_t));

memset(result,0,(textlen+1)*sizeof(wchar_t));

MultiByteToWideChar(CP_ACP, 0,buf,-1,(LPWSTR)result,textlen );

return result;
}

//Unicode转成UTF8
char* Ansi22Utf8::UnicodeToUtf8(const wchar_t* buf)
{
char* result;

int textlen = 0;

textlen = WideCharToMultiByte( CP_UTF8, 0, buf, -1, NULL, 0, NULL, NULL );

result =(char *)malloc((textlen+1)*sizeof(char));

memset(result, 0, sizeof(char) * ( textlen + 1 ) );

WideCharToMultiByte( CP_UTF8, 0, buf, -1, result, textlen, NULL, NULL );

return result;
}

char* Ansi22Utf8::AnsiToUtf8(const char* szAnsi)
{
/* if (szAnsi == NULL)
return NULL ;

_bstr_t bstrTmp (szAnsi) ;
int nLen = ::WideCharToMultiByte (CP_UTF8, 0, (LPCWSTR)bstrTmp, -1, NULL, 0, NULL, NULL) ;
char * pUTF8 = new char[nLen+1] ;
ZeroMemory (pUTF8, nLen + 1) ;
::WideCharToMultiByte (CP_UTF8, 0, (LPCWSTR)bstrTmp, -1, pUTF8, nLen, NULL, NULL) ;
return pUTF8 ;
*/

return UnicodeToUtf8(AnsiToUnicode(szAnsi));
}