Chinaunix首页 | 论坛 | 博客
  • 博客访问: 569385
  • 博文数量: 137
  • 博客积分: 4040
  • 博客等级: 上校
  • 技术积分: 1584
  • 用 户 组: 普通用户
  • 注册时间: 2009-01-08 13:05
文章分类

全部博文(137)

文章存档

2011年(10)

2010年(23)

2009年(104)

分类: LINUX

2009-12-30 16:18:29

在现在的软件工程当中,一个项目的完工并不可能只用到一种语言,往往会用到好几种语言相互配合才能完成整个工程。这就会遇到不同语言之间相互通信的问题,以及不同语言采用不同编码的转化问题,处理不好汉字将会产生乱码。

当今最流行的编程语言当属JAVA和C类语言,就以此为例加以说明。

JAVA一般采用UTF8的编码方式,而C类语言一般采用Unicode编码方式,则,UTF8编码转Unicode编码函数如下:



string textUTF8;
string textUnicode;
textUnicode=UTF8toUnicode((char *)textUTF8.c_str());

........

string UTF8toUnicode(char *s)
 {
     int len = 0;
     WCHAR* r = new WCHAR[strlen(s) * 2];
     while(s[0])
     {
         int bytes = 1;
         if(s[0] & 0x80)
            while(s[0] & (0x80 >> bytes)) bytes++;
         if(bytes == 1)
                r[len] = s[0];
         else
         {
                r[len] = 0;
                for(char*p = s + (bytes - 1); p > s; p--)
                 r[len] |= ((*p) & 0x3F) << ((bytes - (p - s) - 1) * 6);
                r[len] |= (s[0] & ((1 << (7 - bytes)) - 1)) << ((bytes - 1) * 6);
         }
         len++;
         s += bytes;
     }
     r[len] = 0;
     char*buffer = new char[len * 2 + 1];
     ZeroMemory(buffer, len * 2 + 1);
     ::WideCharToMultiByte(CP_ACP, NULL, r, len, buffer, 1+ 2 * len, NULL, NULL);
     string str = buffer;
     delete[] r;
     delete[] buffer;
     return str;
 }


阅读(922) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~