UTF8-GBK WideCharToMultiByte MultiByteToWideChar

//MFC版本

CString UTF8ToGBK(const CString& strUTF8)
{
//确定转换为Unicode需要多少缓冲区(返回值也包含了最后一个NULL字符)
int len = MultiByteToWideChar(CP_UTF8, 0, strUTF8, -1, NULL, 0);
unsigned short * wszGBK = new unsigned short[len + 1];
memset(wszGBK, 0, len * 2 + 2);
MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)strUTF8, -1, (LPWSTR)wszGBK, len);

len = WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)wszGBK, -1, NULL, 0, NULL, NULL);
char *szGBK = new char[len + 1];
memset(szGBK, 0, len + 1);
WideCharToMultiByte(CP_ACP,0, (LPCWSTR)wszGBK, -1, szGBK, len, NULL, NULL);
CString gbkCString(szGBK);
delete[]szGBK;
delete[]wszGBK;
return gbkCString;
}

//C++标准版本

std::string GBKToUTF8(const std::string& strGBK)
{
 std::string strOutUTF8 = "";
 WCHAR * str1;
 int n = MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, NULL, 0);
 str1 = new WCHAR[n];
 MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, str1, n);
 n = WideCharToMultiByte(CP_UTF8, 0, str1, -1, NULL, 0, NULL, NULL);
 char * str2 = new char[n];
 WideCharToMultiByte(CP_UTF8, 0, str1, -1, str2, n, NULL, NULL);
 strOutUTF8 = str2;
 delete[]str1;
 str1 = NULL;
 delete[]str2;
 str2 = NULL;
 return strOutUTF8;
}

转载于:https://www.cnblogs.com/coolbear/p/3718892.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MultiByteToWideChar和WideCharToMultiByte是Windows API函数,用于进行字符集转换。其中,MultiByteToWideChar函数将多字节字符转换为宽字符,而WideCharToMultiByte函数则将宽字符转换为多字节字符。下面是它们的使用方式: MultiByteToWideChar函数的使用方式: ``` int MultiByteToWideChar( UINT CodePage,//字符集编码 DWORD dwFlags,//转换标志 LPCSTR lpMultiByteStr,//待转换的多字节字符 int cbMultiByte,//待转换的多字节字符长度 LPWSTR lpWideCharStr,//用于接收转换结果的缓冲区 int cchWideChar//缓冲区长度 ); ``` WideCharToMultiByte函数的使用方式: ``` int WideCharToMultiByte( UINT CodePage,//字符集编码 DWORD dwFlags,//转换标志 LPCWSTR lpWideCharStr,//待转换的宽字符 int cchWideChar,//待转换的宽字符长度 LPSTR lpMultiByteStr,//用于接收转换结果的缓冲区 int cbMultiByte,//缓冲区长度 LPCSTR lpDefaultChar,//未能转换的字符用于替代的字符集 LPBOOL lpUsedDefaultChar//是否替换字符 ); ``` CodePage参数指定了字符集的编码方式,常用的字符集如UTF-8、GBK等。 dwFlags参数可以控制字符集转换的行为,例如控制是否使用默认字符集替换无法转换的字符。 lpMultiByteStr和lpWideCharStr参数分别为待转换的多字节字符和宽字符。 cbMultiByte和cchWideChar参数分别指定了转换缓冲区的长度。 使用时,需要根据实际情况调用这两个函数进行字符集转换。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值