C++中UTF-8与GBK转换需依赖系统API或第三方库:Windows用MultiByteToWideChar/WideCharToMultiByte经UTF-16中转,Linux/macOS用iconv,跨平台推荐Boost.Locale;标准C++不内置该功能。

在C++中做UTF-8和GBK编码转换,核心是借助系统API或第三方库完成字节流的重新解释与映射。Windows平台可用MultiByteToWideChar和WideCharToMultiByte配合UTF-16中转;Linux/macOS推荐用iconv;跨平台项目可选utf8cpp或Boost.Locale。纯标准C++不内置编码转换功能。
Windows下用WinAPI双向转换(UTF-8 ↔ GBK)
Windows API以UTF-16(wchar_t)为桥梁:先将源编码转为UTF-16,再转为目标编码。注意CP_UTF8和936(GBK代码页)的使用。
示例:UTF-8字符串转GBK
#include <windows.h>
#include <string>
std::string utf8_to_gbk(const std::string& utf8_str) {
if (utf8_str.empty()) return {};
// UTF-8 → UTF-16
int wlen = MultiByteToWideChar(CP_UTF8, 0, utf8_str.c_str(), -1, nullptr, 0);
if (wlen == 0) return {};
std::wstring wstr(wlen, L'\0');
MultiByteToWideChar(CP_UTF8, 0, utf8_str.c_str(), -1, &wstr[0], wlen);
// UTF-16 → GBK (code page 936)
int len = WideCharToMultiByte(936, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);
if (len == 0) return {};
std::string gbk_str(len, '\0');
WideCharToMultiByte(936, 0, wstr.c_str(), -1, &gbk_str[0], len, nullptr, nullptr);
gbk_str.pop_back(); // 去掉末尾的'\0'
return gbk_str;
}
std::string gbk_to_utf8(const std::string& gbk_str) {
if (gbk_str.empty()) return {};
// GBK → UTF-16
int wlen = MultiByteToWideChar(936, 0, gbk_str.c_str(), -1, nullptr, 0);
if (wlen == 0) return {};
std::wstring wstr(wlen, L'\0');
MultiByteToWideChar(936, 0, gbk_str.c_str(), -1, &wstr[0], wlen);
// UTF-16 → UTF-8
int len = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);
if (len == 0) return {};
std::string utf8_str(len, '\0');
WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, &utf8_str[0], len, nullptr, nullptr);
utf8_str.pop_back();
return utf8_str;
}登录后复制
Linux/macOS下用iconv转换
iconv是POSIX标准接口,需链接-liconv(macOS可能需额外安装)。支持“UTF-8”和“GBK”(部分系统也认“CP936”或“GB18030”)。
立即学习“C++免费学习笔记(深入)”;
标签: linux windows 编码 字节 mac c++ macos win 常见问题 cos
还木有评论哦,快来抢沙发吧~