UTF-8 转 GB2312
#include <windows.h>
#include <string>
#include <vector>
std::string Utf8ToGb2312(const std::string& utf8) {
int len = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, nullptr, 0);
std::vector<wchar_t> wideCharStr(len);
MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, &wideCharStr[0], len);
len = WideCharToMultiByte(936, 0, &wideCharStr[0], -1, nullptr, 0, nullptr, nullptr);
std::vector<char> gb2312Str(len);
WideCharToMultiByte(936, 0, &wideCharStr[0], -1, &gb2312Str[0], len, nullptr, nullptr);
return std::string(gb2312Str.begin(), gb2312Str.end() - 1);
}
GB2312 转 UTF-8
std::string Gb2312ToUtf8(const std::string& gb2312) {
int len = MultiByteToWideChar(936, 0, gb2312.c_str(), -1, nullptr, 0);
std::vector<wchar_t> wideCharStr(len);
MultiByteToWideChar(936, 0, gb2312.c_str(), -1, &wideCharStr[0], len);
len = WideCharToMultiByte(CP_UTF8, 0, &wideCharStr[0], -1, nullptr, 0, nullptr, nullptr);
std::vector<char> utf8Str(len);
WideCharToMultiByte(CP_UTF8, 0, &wideCharStr[0], -1, &utf8Str[0], len, nullptr, nullptr);
return std::string(utf8Str.begin(), utf8Str.end() - 1);
}
Unicode 转 ANSI
std::string UnicodeToANSI(const std::wstring& unicodeStr) {
int len = WideCharToMultiByte(CP_ACP, 0, unicodeStr.c_str(), -1, nullptr, 0, nullptr, nullptr);
std::vector<char> ansiStr(len);
WideCharToMultiByte(CP_ACP, 0, unicodeStr.c_str(), -1, &ansiStr[0], len, nullptr, nullptr);
return std::string(ansiStr.begin(), ansiStr.end() - 1);
}
ANSI 转 Unicode
std::wstring ANSIToUnicode(const std::string& ansiStr) {
int len = MultiByteToWideChar(CP_ACP, 0, ansiStr.c_str(), -1, nullptr, 0);
std::vector<wchar_t> unicodeStr(len);
MultiByteToWideChar(CP_ACP, 0, ansiStr.c_str(), -1, &unicodeStr[0], len);
return std::wstring(unicodeStr.begin(), unicodeStr.end() - 1);
}