Last active
March 23, 2025 11:03
-
-
Save rosasurfer/ec3bfcd2974a065fd56231de2d70bda8 to your computer and use it in GitHub Desktop.
Encoding conversion in C++
This file contains hidden or 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 UTF-16 string to an ANSI string. | |
std::string utf16ToAnsi(const std::wstring &wstr) { | |
size_type length = wstr.size(); | |
int bufSize = WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK, &wstr[0], length, NULL, 0, NULL, NULL); | |
std::string strTo(bufSize + 1, 0); | |
WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK, &wstr[0], length, &strTo[0], bufSize, NULL, NULL); | |
return strTo; | |
} | |
// Convert a UTF-16 string to an UTF-8 string. | |
std::string utf16ToUtf8(const std::wstring &wstr) { | |
size_type length = wstr.size(); | |
int bufSize = WideCharToMultiByte(CP_UTF8, WC_COMPOSITECHECK, &wstr[0], length, NULL, 0, NULL, NULL); | |
std::string strTo(bufSize + 1, 0); | |
WideCharToMultiByte(CP_UTF8, WC_COMPOSITECHECK, &wstr[0], length, &strTo[0], bufSize, NULL, NULL); | |
return strTo; | |
} | |
// Convert a UTF-8 string to a UTF-16 string. | |
std::wstring utf8ToUtf16(const std::string &str) { | |
size_type length = str.size(); | |
int bufSize = MultiByteToWideChar(CP_UTF8, 0, &str[0], length, NULL, 0); | |
std::wstring wstrTo(bufSize + 1, 0); | |
MultiByteToWideChar(CP_UTF8, 0, &str[0], length, &wstrTo[0], bufSize); | |
return wstrTo; | |
} | |
// Convert a UTF-8 string to an ANSI string. | |
std::string WINAPI utf8ToAnsi(const std::string &str) { | |
return utf16ToAnsi(utf8ToUtf16(str)); | |
} | |
// Convert an ANSI string to a UTF-16 string. | |
std::wstring ansiToUtf16(const std::string &str) { | |
size_type length = str.size(); | |
int bufSize = MultiByteToWideChar(CP_ACP, 0, &str[0], length, NULL, 0); | |
std::wstring wstrTo(bufSize + 1, 0); | |
MultiByteToWideChar(CP_ACP, 0, &str[0], length, &wstrTo[0], bufSize); | |
return wstrTo; | |
} | |
// Convert an ANSI string to a UTF-8 string. | |
std::string WINAPI ansiToUtf8(const std::string &str) { | |
return utf16ToUtf8(ansiToUtf16(str)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment