From 32c2c860d9d45110118769da48b99c24fc0dc749 Mon Sep 17 00:00:00 2001 From: luocai Date: Thu, 13 Jun 2024 10:08:09 +0800 Subject: [PATCH] Add utf8 to gbk function. --- Universal/StringUtility.cpp | 20 ++++++++++++++++++++ Universal/StringUtility.h | 1 + 2 files changed, 21 insertions(+) diff --git a/Universal/StringUtility.cpp b/Universal/StringUtility.cpp index 9ffad08..17b7acb 100644 --- a/Universal/StringUtility.cpp +++ b/Universal/StringUtility.cpp @@ -96,5 +96,25 @@ slow: return true; } +std::string UTF8ToGBK(const std::string &utf8Str) { + int wideStrLen = MultiByteToWideChar(CP_UTF8, 0, utf8Str.c_str(), -1, NULL, 0); + if (wideStrLen == 0) { + return ""; + } + + std::wstring wideStr(wideStrLen, 0); + MultiByteToWideChar(CP_UTF8, 0, utf8Str.c_str(), -1, &wideStr[0], wideStrLen); + + int gbkStrLen = WideCharToMultiByte(CP_ACP, 0, wideStr.c_str(), -1, NULL, 0, NULL, NULL); + if (gbkStrLen == 0) { + return ""; + } + + std::string gbkStr(gbkStrLen, 0); + WideCharToMultiByte(CP_ACP, 0, wideStr.c_str(), -1, &gbkStr[0], gbkStrLen, NULL, NULL); + + return gbkStr; +} + } // namespace StringUtility } // namespace Amass diff --git a/Universal/StringUtility.h b/Universal/StringUtility.h index 7da127c..5161557 100644 --- a/Universal/StringUtility.h +++ b/Universal/StringUtility.h @@ -61,6 +61,7 @@ std::string_view utf8At(const std::string &text, size_t index); size_t utf8CharacterByteSize(const char *character); std::wstring stringToWString(const std::string &string); std::string wstringToString(const std::wstring &string); +std::string UTF8ToGBK(const std::string &utf8Str); } // namespace StringUtility