Chinaunix首页 | 论坛 | 博客
  • 博客访问: 571300
  • 博文数量: 79
  • 博客积分: 2513
  • 博客等级: 少校
  • 技术积分: 806
  • 用 户 组: 普通用户
  • 注册时间: 2006-10-04 18:46
文章分类

全部博文(79)

文章存档

2014年(1)

2010年(5)

2009年(8)

2008年(11)

2007年(41)

2006年(13)

我的朋友

分类: WINDOWS

2007-06-28 17:24:10

在 Windows 下进行编码转换,比较完备的是使用 MultiByteToWideChar 和 WideCharToMultiByte 进行。编码转换的要义是,可以将任何的源编码转换成 Unicode,然后转换到目标编码。比如下面例子是转换 UTF-8 到 GB 的:

// 将字符串从 UTF-8 编码转换到 GBK 编码

string UTF8ToGBK(string utf8)
{
    int len = (int)utf8.size();
    int u_len = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), len, NULL, 0);


    vector<WCHAR> unicode_str(u_len);
    WCHAR* u_str = &unicode_str.front();
    MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), len, u_str, u_len);

    int g_len = WideCharToMultiByte(936, 0, u_str, u_len, NULL, 0, NULL, NULL);


    vector<char> gbk_str(g_len);
    char* g_str = &gbk_str.front();
    WideCharToMultiByte(936, 0, u_str, u_len, g_str, g_len, NULL, NULL);
    
    return string(gbk_str.begin(), gbk_str.end());
}


需要注意的是,std::string 不一定适合用来表示所有的编码,比如 Unicode 用 std::string 来表示就是不合适的。
阅读(1568) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~