资源描述:
《linux操作系统下汉字编码的转换》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、Linux操作系统下汉字编码的转换因为项目的需要linux下将GBK编码转换为utf8编码,google一下,网上的相关资源比较少,下面的操作经过本人的反复试验。本例子同样适用于其他的编码转换。 有gbk到utf8的转换过程,需要经过unicode作为中间编码。因为Windows的转换相对简单,先讲一下windows下的转换过程,linux下的过程基本相同,函数使用上有差别。 Windows下: 1、在windows下可以使用函数MultiByteToWideChar先将多字节字符,转换为unicode。 2、使用函数WideCharToMultiByte,将uni
2、code再转换为utf8编码。 google一下,网上例子很多。在这里贴了一个简单的源码,实现ansi到utf8编码的转换 viewplain char*multichar_2_utf8(constchar*m_string) { intlen=0; wchar_t*w_string; char*utf8_string; //计算由ansi转换为unicode后,unicode编码的长度 len=MultiByteToWideChar(CP_ACP,0,(LPCTSTR)m_string,-1,NULL,0);//CP_ACP指示了转换为unicode编码
3、的编码类型 w_string=(wchar_t*)malloc(2*len+2); memset(w_string,0,2*len+2); //ansi到unicode转换 MultiByteToWideChar(CP_ACP,0,(LPCTSTR)m_string,-1,w_string,len);//CP_ACP指示了转换为unicode编码的编码类型 //计算unicode转换为utf8后,utf8编码的长度 len=WideCharToMultiByte(CP_UTF8,0,w_string,-1,NULL,0,NULL,NULL);//CP_UTF8指
4、示了unicode转换为的类型 utf8_string=(char*)malloc(len+1); memset(utf8_string,0,len+1); //unicode到utf8转换 WideCharToMultiByte(CP_UTF8,0,w_string,-1,utf8_string,len,NULL,NULL);//CP_UTF8指示了unicode转换为的类型 free(w_string); returnutf8_string; } Linux下: linux下没有上面的两个函数,需要使用函数mbstowcs和wcstombs mbst
5、owcs将多字节编码转换为宽字节编码 wcstombs将宽字节编码转换为多字节编码 这两个函数,转换过程中受到系统编码类型的影响,需要通过设置来设定转换前和转换后的编码类型。通过函数setlocale进行系统编码的设置。 linux下输入命名 locale-a查看系统支持的编码类型。 viewplain andy@andy-linux:~$locale-a C en_AG en_AU.utf8 en_BW.utf8 en_CA.utf8 en_DK.utf8 en_GB.utf8 en_HK.utf8 en_IE.utf8 en_IN en
6、_NG en_NZ.utf8 en_PH.utf8 en_SG.utf8 en_US.utf8 en_ZA.utf8 en_ZW.utf8 POSIX zh_CN.gb18030 zh_CN.gbk zh_CN.utf8 zh_HK.utf8 zh_SG.utf8 zh_TW.utf8 本例子中实现的是由zh_CN.gbk到zh_CN.utf8的转换 流程: 1、调用函数setlocale(LC_ALL,"zh_CN.gbk"),设置待转码的字符串类型为gbk类型。 2、调用函数mbstowcs,实现1设置的编码到unicode编码的转换。
7、 3、调用函数setlocale(LC_ALL,"zh_CN.utf8"),设置转换后编码类型为utf8类型。 4、调用函数wcstombs,实现unicode到3设置的编码类型的转换。 下面是我写的源码 viewplain #include #include /****************************************************************************** *FUNCTION:gbk2utf8 *DESCRIPTION:实现由gbk编码