最近在写根据汉字首字母的查询功能,要获取汉字的首字母需要把Unicode的编码转换成GB的编码才能获取汉字的首字母,所以学习了下Symbian上Unicode到GB的编码转换。
下面是简单的算法:(注:由于标准C接口通用性更强容易做平台移植,所以转换的接口用了标准C的字符串而没有用Symbian的描述符)
///<如果wchar 报错的话 请做如下的定义
typedef unsigned short wchar;
/*
* 从Unicode转换成 GBK.
*
* @param unicodeStr 待转换的字符串
*
* @return 转换后的字符串,调用者负责释放内存
*/
char* Unicode2Gbk(wchar* unicodeStr)
{
char* gbkstr = NULL;
if (unicodeStr)
{
int length = 0;
RFs aFileServerSession;
aFileServerSession.Connect();
CCnvCharacterSetConverter* converter =
CCnvCharacterSetConverter::NewLC();
if (converter->PrepareToConvertToOrFromL(KCharacterSetIdentifierGb2312,
aFileServerSession) != CCnvCharacterSetConverter::EAvailable)
User::Leave(KErrNotSupported);
TInt state = CCnvCharacterSetConverter::KStateDefault;
TPtrC16 str;
str.Set(unicodeStr, wcslen(unicodeStr));
HBufC8* iInfoText = HBufC8::NewL(str.Length() * sizeof(wchar));
TPtr8 ptr = iInfoText->Des();
if (CCnvCharacterSetConverter::EErrorIllFormedInput
== converter->ConvertFromUnicode(ptr, str, state))
User::Leave(KErrArgument);
length = ptr.Length();
if (length > 0)
{
gbkstr = (char*)malloc((length + 1) * sizeof(char));
if (gbkstr)
{
memset(gbkstr, 0x00, (length + 1) * sizeof(char));
memcpy((void*)gbkstr, (void*)ptr.Ptr(), length * sizeof(char));
}
}
aFileServerSession.Close();
CleanupStack::PopAndDestroy();
delete iInfoText;
}
return gbkstr;
}
wchar* Gbk2Unicode(char* gbkstr)
{
wchar* unicodeStr = NULL;
if(gbkstr)
{
int length = 0;
RFs aFileServerSession;
aFileServerSession.Connect();
CCnvCharacterSetConverter* converter = CCnvCharacterSetConverter::NewLC();
if (converter->PrepareToConvertToOrFromL(KCharacterSetIdentifierGb2312,
aFileServerSession) != CCnvCharacterSetConverter::EAvailable)
User::Leave(KErrNotSupported);
TInt state = CCnvCharacterSetConverter::KStateDefault;
TPtrC8 str;
str.Set(gbkstr, (int)strlen(gbkstr));
HBufC* iInfoText = HBufC::NewL(str.Length());
TPtr16 ptr = iInfoText->Des();
if (CCnvCharacterSetConverter::EErrorIllFormedInput
== converter->ConvertToUnicode(ptr, str, state))
User::Leave(KErrArgument);
length = ptr.Length();
if(length > 0)
{
unicodeStr = (wchar*)malloc((length + 1) * sizeof(wchar));
if(unicodeStr)
{
memset(unicodeStr, 0x00, (length + 1) * sizeof(wchar));
memcpy((void*)unicodeStr, (void*)ptr.Ptr(), length * sizeof(wchar));
}
}
aFileServerSession.Close();
CleanupStack::PopAndDestroy();
delete iInfoText;
}
return unicodeStr;
}
如果 wcslen 函数无法用的话 请实现自己的Unicode字符串获取长度的函数。另外Unicode2Gbk 这个函数我测试过,Gbk2Unicode 是依照逻辑实现的但没有测试,如果有问题的话可以通知我。谢谢!希望对大家有用。