当前位置:   article > 正文

C++中GBK、Unicode、UTF8字符串之间的转换方法_c++gbk转unicode

c++gbk转unicode

wchar_t* UTF8ToUnicode(const char szU8)
{
int wcsLen = ::MultiByteToWideChar(CP_UTF8, NULL, szU8, strlen(szU8), NULL, 0);
//分配空间要给’\0’留个空间,MultiByteToWideChar不会给’\0’空间
wchar_t
wszString = new wchar_t[wcsLen + 1];
//转换
::MultiByteToWideChar(CP_UTF8, NULL, szU8, strlen(szU8), wszString, wcsLen);
//最后加上’\0’
wszString[wcsLen] = ‘\0’;
return wszString;
}
char* UnicodeToUTF8(wchar_t wszString)
{
//预转换,得到所需空间的大小,这次用的函数和上面名字相反
int u8Len = ::WideCharToMultiByte(CP_UTF8, NULL, wszString, wcslen(wszString), NULL, 0, NULL, NULL);
//同上,分配空间要给’\0’留个空间
//UTF8虽然是Unicode的压缩形式,但也是多字节字符串,所以可以以char的形式保存
char
szU8 = new char[u8Len + 1];
//转换
//unicode版对应的strlen是wcslen
::WideCharToMultiByte(CP_UTF8, NULL, wszString, wcslen(wszString), szU8, u8Len, NULL, NULL);
//最后加上’\0’
szU8[u8Len] = ‘\0’;
return szU8;
}
char* UnicodeToGB2312(wchar_t* szUnicodeString)
{
UINT nCodePage = 936; //GB2312
int nLength=WideCharToMultiByte(nCodePage,0,szUnicodeString,-1,NULL,0,NULL,NULL);
char* pBuffer=new char[nLength+1];
WideCharToMultiByte(nCodePage,0,szUnicodeString,-1,pBuffer,nLength,NULL,NULL);
pBuffer[nLength]=0;
return pBuffer;
}
wchar_t* GB2312ToUnicode(const char* szGBString)
{
UINT nCodePage = 936; //GB2312
int nLength=MultiByteToWideChar(nCodePage,0,szGBString,-1,NULL,0);
wchar_t* pBuffer = new wchar_t[nLength+1];
MultiByteToWideChar(nCodePage,0,szGBString,-1,pBuffer,nLength);
pBuffer[nLength]=0;
return pBuffer;
}
char* UTF8ToGBK2312(const char *szU8)
{
wchar_t *wszString = UTF8ToUnicode(szU8);
char szString = UnicodeToGB2312(wszString);
delete[] wszString;
return szString;
}
char
GBK2312ToUTF8(const char *szGBK)
{
wchar_t *wszString = GB2312ToUnicode(szGBK);
char *szString = UnicodeToUTF8(wszString);
delete[] wszString;
return szString;
}

使用实例:
char *pGBKString1=“一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十”;
char *pUTF8String1 = GBK2312ToUTF8(pGBKString1 );
char *pGBKString3=“A373129EB97E05AF5161BCC0CEC2C60D92D9C3EFAF90D53A70”;
char *pUTF8String2 = GBK2312ToUTF8(pGBKString2 );
char *pGBKString2=“A373129EB97E1BF90536F7DE9D88DD1A82DECFB5A9D1DB”;
char *pUTF8String2 = GBK2312ToUTF8(pGBKString2 );
char *pUTF8String3 = GBK2312ToUTF8(pGBKString3 );
::MessageBoxA(NULL,pUTF8String1,“String1”,MB_OK);
::MessageBoxA(NULL,pUTF8String2,“String2”,MB_OK);
::MessageBoxA(NULL,pUTF8String3,“String1”,MB_OK);
delete [] pUTF8String1;
delete [] pUTF8String2;
delete [] pUTF8String3;

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/123139
推荐阅读
相关标签
  

闽ICP备14008679号