windows c++11 GB18030/UTF-8转换
时间: 2024-05-14 15:19:03 浏览: 157
在 Windows 平台下,可以使用 MultiByteToWideChar 和 WideCharToMultiByte 函数来完成 GB18030/UTF-8 和 Unicode 编码之间的转换。
GB18030/UTF-8 转 Unicode:
```
std::wstring utf8_to_wstring(const std::string& str)
{
int length = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
wchar_t* buffer = new wchar_t[length];
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, buffer, length);
std::wstring result(buffer);
delete[] buffer;
return result;
}
std::wstring gb_to_wstring(const std::string& str)
{
int length = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);
wchar_t* buffer = new wchar_t[length];
MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, buffer, length);
std::wstring result(buffer);
delete[] buffer;
return result;
}
```
Unicode 转 GB18030/UTF-8:
```
std::string wstring_to_utf8(const std::wstring& str)
{
int length = WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, NULL, 0, NULL, NULL);
char* buffer = new char[length];
WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, buffer, length, NULL, NULL);
std::string result(buffer);
delete[] buffer;
return result;
}
std::string wstring_to_gb(const std::wstring& str)
{
int length = WideCharToMultiByte(CP_ACP, 0, str.c_str(), -1, NULL, 0, NULL, NULL);
char* buffer = new char[length];
WideCharToMultiByte(CP_ACP, 0, str.c_str(), -1, buffer, length, NULL, NULL);
std::string result(buffer);
delete[] buffer;
return result;
}
```
需要注意的是,GB18030/UTF-8 转 Unicode 时,使用的是 CP_UTF8 编码;Unicode 转 GB18030/UTF-8 时,使用的是 CP_ACP 编码。
阅读全文