eXile 的专栏

utf8编码转换


     只用于 Windows 平台.

using std::string;
using std::vector;

inline 
string utf8_trans_impl(string const& from, int from_code, int to_code)
{
    
int len16 = MultiByteToWideChar(from_code, 0, from.begin(), from.size(), 00);
    
if (len16 > 0)
    {
        vector
<wchar_t> ucs2_buf(len16, 0);
        len16 
= MultiByteToWideChar(from_code, 0, from.begin(), from.size(), ucs2_buf.begin(), len16);
        
        
int len8 = WideCharToMultiByte(to_code, 0, ucs2_buf, len16, 0,  000);
        
string result(len8, 0);
        WideCharToMultiByte(to_code, 
0, ucs2_buf.begin(), len16, result.begin(),  len8, 00);
        return result;
    }
    
       return  
string();
}

inline string  from_utf8(
string const& from)
{    
    return utf8_trans_impl( from, CP_UTF8, CP_ACP);
}

inline string  to_utf8(
string const& from)
{    
    return utf8_trans_impl(from, CP_ACP, CP_UTF8);
}


     转载请表明原文地址:  http://www.cppblog.com/exile/

posted on 2008-04-16 01:26 eXile 阅读(3725) 评论(5)  编辑 收藏 引用 所属分类: C/C++代码片段

评论

# re: utf8编码转换 2008-04-16 11:06 想酷就要勤

linux下用shell脚本很容易搞定的 呵呵  回复  更多评论   

# re: utf8编码转换 2008-04-16 23:26 李侃

我之前也写过一个,和这个基本一样。
不过还是收藏了。

谢谢!  回复  更多评论   

# re: utf8编码转换 2008-07-23 21:28 spirit

大哥不知道你有没有测试你的代码?
from.begin()返回的是iterator,在MultiByteToWideChar中可以直接用吗?
如果说可以用from.c_str()更正,那么ucs2_buf.begin()呢?

  回复  更多评论   

# re: utf8编码转换 2008-07-23 23:03 eXile

@spirit
我用的mingw, 没有注意到这个问题, 但是由于VC平台的iterator并不是原生指针,所以正确的写法应该是 &ucs2_buf[0]
  回复  更多评论   

# re: utf8编码转换[未登录] 2008-07-30 22:47 foxtail

这个我在scintilla的代码里看过类似的  回复  更多评论   


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


导航

<2008年4月>
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

统计

常用链接

留言簿(18)

随笔分类

随笔档案

服务器编程

搜索

最新评论

阅读排行榜

评论排行榜