c++怎么进行UTF-8和GBK编码转换_c++ UTF-8/GBK编码转换方法

在C++中转换UTF-8与GBK编码需借助第三方库或系统API。Windows平台可使用MultiByteToWideChar和WideCharToMultiByte,先转Unicode再互转;跨平台可用iconv库,通过code_convert函数实现;推荐使用Boost.Locale,提供简洁接口并支持多后端

c++怎么进行utf-8和gbk编码转换_c++ utf-8/gbk编码转换方法

在C++中进行UTF-8和GBK编码转换,由于标准库不直接支持这些编码格式,需要借助第三方库或调用系统API来实现。以下是几种常见且实用的方法。

使用Windows API进行转换

在Windows平台上,可以使用MultiByteToWideChar和WideCharToMultiByte函数完成UTF-8与GBK之间的转换。基本思路是:先将UTF-8转为Unicode(UTF-16),再从Unicode转为GBK,反之亦然。

UTF-8 转 GBK 示例代码:

// UTF-8 转 GBK std::string utf8_to_gbk(const std::string& utf8) { int len = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, NULL, 0); std::wstring wstr(len, 0); MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, &wstr[0], len);

len = WideCharToMultiByte(936, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);  std::string gbk(len - 1, 0);  WideCharToMultiByte(936, 0, wstr.c_str(), -1, &gbk[0], len, NULL, NULL);  return gbk;  

}

GBK 转 UTF-8 示例代码:

// GBK 转 UTF-8 std::string gbk_to_utf8(const std::string& gbk) { int len = MultiByteToWideChar(936, 0, gbk.c_str(), -1, NULL, 0); std::wstring wstr(len, 0); MultiByteToWideChar(936, 0, gbk.c_str(), -1, &wstr[0], len);

len = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);  std::string utf8(len - 1, 0);  WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, &utf8[0], len, NULL, NULL);  return utf8;  

}

使用iconv库(跨平台方案)

iconv是GNU提供的字符集转换库,支持多种编码,在Linux和macOS上原生支持,Windows可通过MinGW或libiconv引入。

编译时需链接libiconv:

立即学习“C++免费学习笔记(深入)”;

g++ main.cpp -liconv

示例代码(UTF-8 转 GBK):

#include

std::string code_convert(const std::string& source_str, const char from_charset, const char to_charset) {
iconv_t cd = iconv_open(to_charset, from_charset);
if (cd == (iconv_t)-1) return “”;

size_t in_len = source_str.length();  size_t out_len = in_len * 4;  std::string result(out_len, 0);  char* in_buf = const_cast(source_str.c_str());  char* out_buf = &result[0];  size_t ret = iconv(cd, &in_buf, &in_len, &out_buf, &out_len);  iconv_close(cd);  if (ret == (size_t)-1) return "";  result.resize(result.size() - out_len);  return result;  

}

// 使用方式
std::string utf8_str = “你好”;
std::string gbk_str = code_convert(utf8_str, “UTF-8”, “GBK”);

使用Boost.Locale(推荐用于新项目)

Boost.Locale提供了简洁的接口进行编码转换,底层可基于ICU、iconv或WinAPI,适合跨平台开发。

示例:

#include

std::string utf8_to_gbk_boost(const std::string& utf8) {
return boost::locale::conv::to_utf(utf8, “GBK”);
// 或使用 conv::from_utf 转换方向
}

需要链接Boost.System和Boost.Locale库。

基本上就这些常用方法。Windows下用API最方便,跨平台建议用iconv或Boost。注意处理中文字符时确保输入合法,避免乱码。

以上就是c++++怎么进行UTF-8和GBK编码转换_c++ UTF-8/GBK编码转换方法的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1482069.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月19日 06:03:45
下一篇 2025年12月19日 06:03:54

相关推荐

发表回复

登录后才能评论
关注微信