57 lines
1.8 KiB
C++
57 lines
1.8 KiB
C++
#include <windows.h>
|
|
#include <string>
|
|
|
|
/**
|
|
* 将本地多字节字符串 (ANSI/GBK) 转换为 UTF-8
|
|
*/
|
|
inline std::string ansi_to_utf8(const std::string& ansi_str) {
|
|
if (ansi_str.empty()) return "";
|
|
|
|
// 1. ANSI -> UTF-16 (WideChar)
|
|
int wlen = MultiByteToWideChar(CP_ACP, 0, ansi_str.c_str(), -1, NULL, 0);
|
|
std::wstring wstr(wlen, 0);
|
|
MultiByteToWideChar(CP_ACP, 0, ansi_str.c_str(), -1, &wstr[0], wlen);
|
|
|
|
// 2. UTF-16 -> UTF-8
|
|
int u8len = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);
|
|
std::string utf8_str(u8len, 0);
|
|
WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, &utf8_str[0], u8len, NULL, NULL);
|
|
|
|
// 移除末尾的 \0
|
|
if (!utf8_str.empty() && utf8_str.back() == '\0') {
|
|
utf8_str.pop_back();
|
|
}
|
|
return utf8_str;
|
|
}
|
|
|
|
/**
|
|
* 将 UTF-8 字符串转换为本地多字节字符串 (ANSI/GBK)
|
|
* 用于在多字节字符集 UI 上正常显示从远程接收到的内容
|
|
*/
|
|
inline std::string utf8_to_ansi(const std::string& utf8_str) {
|
|
if (utf8_str.empty()) return "";
|
|
|
|
// 1. UTF-8 -> UTF-16 (WideChar)
|
|
// 计算需要的宽字符长度
|
|
int wlen = MultiByteToWideChar(CP_UTF8, 0, utf8_str.c_str(), -1, NULL, 0);
|
|
if (wlen <= 0) return "";
|
|
|
|
std::wstring wstr(wlen, 0);
|
|
MultiByteToWideChar(CP_UTF8, 0, utf8_str.c_str(), -1, &wstr[0], wlen);
|
|
|
|
// 2. UTF-16 -> ANSI (Local Code Page, e.g., GBK)
|
|
// CP_ACP 表示使用当前系统的 ANSI 代码页
|
|
int alen = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);
|
|
if (alen <= 0) return "";
|
|
|
|
std::string ansi_str(alen, 0);
|
|
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, &ansi_str[0], alen, NULL, NULL);
|
|
|
|
// 移除 WideCharToMultiByte 自动添加的 \0 结尾
|
|
if (!ansi_str.empty() && ansi_str.back() == '\0') {
|
|
ansi_str.pop_back();
|
|
}
|
|
|
|
return ansi_str;
|
|
}
|