在实际开发中,有可能项目是多字节字符集的,但是要处理的一些网络数据是Unicode字符集的(比如http消息,有时使用的是utf8字符编码,那就使用的是Unicode字符集了)。这时候,就需要进行Unicode字符集和多字节字符集转换了。
下面提供的参考是使用WindowsAPI实现的。
1.utf8字符编码数据 --> Ansi字符编码数据
#include <windows.h>
#include <shlwapi.h>
std::string Utf8ToAnsi(std::string str)
{
// 将string中的 utf-8数据 转存到wstring
int size = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0);
std::wstring utf8Str(size - 1, L'\0');
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, &utf8Str[0], size);
// 将wstring中的 utf-8数据转为ANSI数据 存到string
size = WideCharToMultiByte(CP_ACP, 0, utf8Str.c_str(), -1, nullptr, 0, nullptr, nullptr);
std::string gbkStr = std::string(size - 1, '\0');
WideCharToMultiByte(CP_ACP, 0, utf8Str.c_str(), -1, &gbkStr[0], size, nullptr, nullptr);
return gbkStr;
}
2.Ansi字符编码数据 --> utf8字符编码数据
#include <windows.h>
#include <shlwapi.h>
std::string AnsiToUtf8(std::string str)
{
// 将string中的 ANSI编码数据转utf-8 转存到wstring
int size = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, nullptr, 0);
std::wstring ansiStr(size - 1, L'\0');
MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, &ansiStr[0], size);
// 将wstring中的 utf-8编码数据 存到string
size = WideCharToMultiByte(CP_UTF8, 0, ansiStr.c_str(), -1, nullptr, 0, nullptr, nullptr);
std::string utf8Str = std::string(size - 1, '\0');
WideCharToMultiByte(CP_UTF8, 0, ansiStr.c_str(), -1, &utf8Str[0], size, nullptr, nullptr);
return utf8Str;
}