BOOL achr2wchr( const char *src, wchar_t *dst, int dst_len )
{
size_t len = strlen(src);
size_t wlen = MultiByteToWideChar(CP_ACP, 0, (const char*)src, int(len), NULL, 0);
if (wlen > dst_len)
{
return FALSE;
}
MultiByteToWideChar(CP_ACP, 0, (const char*)src, int(len), (wchar_t*)dst, int(wlen));
return TRUE;
}
BOOL wch2ach( const wchar_t* src, char *dst, int dst_len )
{
size_t wlen = wcslen(src);
size_t len = WideCharToMultiByte(CP_OEMCP, NULL, (const wchar_t*)src, int(wlen), NULL, 0, NULL, FALSE);
if (len > dst_len)
{
return FALSE;
}
WideCharToMultiByte(CP_OEMCP, NULL, (const wchar_t*)src, int(wlen), (char*)dst, int(len), NULL, FALSE);
return TRUE;
}
// 多字节编码转为UTF8编码
bool MBToUTF8(char* pu8, const char* pmb, int u_len)
{
// convert an MBCS string to widechar
int nLen = MultiByteToWideChar(CP_ACP, 0, pmb, -1, NULL, 0);
WCHAR* lpszW = NULL;
try
{
lpszW = new WCHAR[nLen];
}
catch(bad_alloc &memExp)
{
return false;
}
int nRtn = MultiByteToWideChar(CP_ACP, 0, pmb, -1, lpszW, nLen);
if(nRtn != nLen)
{
delete[] lpszW;
return false;
}
// convert an widechar string to utf8
int utf8Len = WideCharToMultiByte(CP_UTF8, 0, lpszW, -1, NULL, 0, NULL, NULL);
if (utf8Len <= 0
|| u_len < utf8Len)
{
delete[] lpszW;
return false;
}
nRtn = WideCharToMultiByte(CP_UTF8, 0, lpszW, nLen, pu8, utf8Len, NULL, NULL);
delete[] lpszW;
return true;
}
// UTF8编码转为多字节编码
bool UTF8ToMB(char* pmb, const char* pu8, int b_len)
{
int nLen = MultiByteToWideChar( CP_UTF8, 0, pu8, -1, NULL, NULL );//得到UTF8编码的字符串长度,是2
LPWSTR lpwsz = new WCHAR[nLen];
MultiByteToWideChar( CP_UTF8, 0, pu8, -1, lpwsz, nLen );//转换的结果是UCS2格式的价值两个字
int nLen1 = WideCharToMultiByte( CP_ACP, 0, lpwsz, nLen, NULL, NULL, NULL, NULL );
if (b_len < nLen1)
{
return false;
}
WideCharToMultiByte( CP_ACP, 0, lpwsz, nLen, pmb, nLen1, NULL, NULL );//转换完毕
delete [] lpwsz;
return true;
}
Unicode 多字节 utf-8互转
最新推荐文章于 2022-06-14 15:14:51 发布