很多时候我们需要UNICODE,utf-8和ascii相互转化,windows提供了相关api但是不是特别好用,很多时候还会出错,封装一份自己的字符转化函数,使用的时候就不用那么麻烦了,需要的时候,直接调用就好。
#pragma once
class CConvertChar
{
public:
CConvertChar() = default;
~CConvertChar();
public:
static int UnicodeToAnsi(LPSTR szAnsi,LPCWSTR wstrUnicode);
static int AnsiToUnicode(LPWSTR wstrUnicode, LPCSTR szAnsi);
static int UTF8ToUnicode(LPWSTR wstrUnicoe, LPCSTR szUTF8);
static int UnicodeToUTF8(LPSTR szUTF8, LPCWSTR wszUnicode);
};
CConvertChar::~CConvertChar()
{
}
int CConvertChar::UnicodeToAnsi(LPSTR szAnsi, LPCWSTR wstrUnicode)
{
DWORD dwMinSize = 0;
//转化后需要多少多字节来存储
dwMinSize = WideCharToMultiByte(CP_OEMCP, 0, wstrUnicode, -1, NULL, 0, NULL, FALSE);
if (0 == dwMinSize)
{
return 0;
}
WideCharToMultiByte(CP_OEMCP, 0,wstrUnicode, -1, szAnsi, dwMinSize, NULL, FALSE);
return dwMinSize;
}
int CConvertChar::AnsiToUnicode(LPWSTR wstrUnicode, LPCSTR szAnsi)
{
DWORD dwMinSize = 0;
dwMinSize = MultiByteToWideChar(CP_ACP, 0, szAnsi, -1, NULL, 0);
if (0 == dwMinSize)
{
return 0;
}
MultiByteToWideChar(CP_ACP, 0,szAnsi, -1,wstrUnicode, dwMinSize);
return dwMinSize;
}
int CConvertChar::UTF8ToUnicode(LPWSTR wstrUnicoe, LPCSTR szUTF8)
{
//转换后Unicode的长度
DWORD dwMinSize = MultiByteToWideChar(CP_UTF8, 0, szUTF8, -1, NULL, 0);
if (0 != dwMinSize)
{
//转为Unicode
dwMinSize = MultiByteToWideChar(CP_UTF8, 0, szUTF8, -1, wstrUnicoe, dwMinSize);
return dwMinSize;
}
return 0;
}
int CConvertChar::UnicodeToUTF8(LPSTR szUTF8, LPCWSTR wszUnicode)
{
int dwMinSize = WideCharToMultiByte(CP_UTF8, 0, wszUnicode, -1, NULL, 0, NULL, NULL);
if (dwMinSize)
{
dwMinSize = WideCharToMultiByte(CP_UTF8, 0, wszUnicode, -1, szUTF8,dwMinSize,NULL,NULL);
}
return dwMinSize;
}