Last active
December 31, 2024 19:47
-
-
Save rosasurfer/ec3bfcd2974a065fd56231de2d70bda8 to your computer and use it in GitHub Desktop.
Encoding conversion in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Convert a wide Unicode string to an ANSI string. | |
std::string unicodeToAnsi(const std::wstring &wstr) { | |
int bufSize = WideCharToMultiByte(CP_ACP, 0, &wstr[0], -1, NULL, 0, NULL, NULL); | |
std::string strTo(bufSize, 0); | |
WideCharToMultiByte(CP_ACP, 0, &wstr[0], (int)wstr.size(), &strTo[0], bufSize, NULL, NULL); | |
return strTo; | |
} | |
// Convert a wide Unicode string to an UTF8 string. | |
std::string unicodeToUtf8(const std::wstring &wstr) { | |
int bufSize = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL); | |
std::string strTo(bufSize, 0); | |
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], bufSize, NULL, NULL); | |
return strTo; | |
} | |
// Convert a UTF8 string to a wide Unicode string. | |
std::wstring utf8ToUnicode(const std::string &str) { | |
int bufSize = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0); | |
std::wstring wstrTo(bufSize, 0); | |
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], bufSize); | |
return wstrTo; | |
} | |
// Convert a UTF-8 string to an ANSI string. | |
std::string WINAPI utf8ToAnsi(const std::string &str) { | |
return unicodeToAnsi(utf8ToUnicode(str)); | |
} | |
// Convert an ANSI string to a wide Unicode (UTF-16) string. | |
std::wstring ansiToUnicode(const std::string &str) { | |
int bufSize = MultiByteToWideChar(CP_ACP, 0, &str[0], (int)str.size(), NULL, 0); | |
std::wstring wstrTo(bufSize, 0); | |
MultiByteToWideChar(CP_ACP, 0, &str[0], (int)str.size(), &wstrTo[0], bufSize); | |
return wstrTo; | |
} | |
// Convert an ANSI string to a UTF-8 string. | |
std::string WINAPI ansiToUtf8(const std::string &str) { | |
return unicodeToUtf8(ansiToUnicode(str)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment