colorful

zc qq:1337220912

 

跨平台的文字编码转换方法

http://blog.csdn.net/serverxp/article/details/5538017

最近在做一套跨平台的短信收发开发程序,遇到了一个问题,那就是文字编码转换。在windowsg下的转换有库函数

MultiByteToWideChar        WideCharToMultiByte,这二个,但是我要的是在linux机器下也可以正常使用,所以google了一天,发现了二个解决方案,一个是libiconv,一个就是ICU了,实际使用后,发现还是ICU更好用,下面是一个简单的例子。

 

 

  1. #include <unicode/ucnv.h>  
  2. #ifdef _WIN32  
  3. #pragma comment(lib, "icuuc.lib")  
  4. #endif  
  5. //返回0为成功,错误代码定义见后面  
  6. int convert(const char *    toConverterName,  
  7.     const char *    fromConverterName,  
  8.     char *  target,  
  9.     int32_t     targetCapacity,  
  10.     const char *    source,  
  11.     int32_t     sourceLength)  
  12. {  
  13.     UErrorCode  error = U_ZERO_ERROR;  
  14.     ucnv_convert(toConverterName,fromConverterName,target,  targetCapacity, source, sourceLength, &error );  
  15.     return error;  
  16. }  
  17. int _tmain(int argc, _TCHAR* argv[])  
  18. {  
  19.     wchar_t aaa[] = L"中国人的系统上123323";  
  20.     int alen = wcslen(aaa);  
  21.     int blen=alen*2+sizeof(int);  
  22.     char *abuff=new char[blen];  
  23.     int result = convert( "gb2312", "utf-16le", abuff, blen, (const char *)aaa, alen);  
  24.     cout << abuff << endl<<strlen(abuff)<<endl;  
  25.     delete []abuff;  
  26.     return 0;  

posted on 2012-07-18 17:31 多彩人生 阅读(477) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

统计

常用链接

留言簿(3)

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜