-
-
Save snowdence/51a2cfccfe533a222b265410123d5ebd 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 UTF8 string | |
std::string utf8_encode(const std::wstring &wstr) | |
{ | |
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL); | |
std::string strTo(size_needed, 0); | |
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL); | |
return strTo; | |
} | |
// Convert an UTF8 string to a wide Unicode String | |
std::wstring utf8_decode(const std::string &str) | |
{ | |
int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0); | |
std::wstring wstrTo(size_needed, 0); | |
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed); | |
return wstrTo; | |
} | |
// Convert an wide Unicode string to ANSI string | |
std::string unicode2ansi(const std::wstring &wstr) | |
{ | |
int size_needed = WideCharToMultiByte(CP_ACP, 0, &wstr[0], -1, NULL, 0, NULL, NULL); | |
std::string strTo(size_needed, 0); | |
WideCharToMultiByte(CP_ACP, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL); | |
return strTo; | |
} | |
// Convert an ANSI string to a wide Unicode String | |
std::wstring ansi2unicode(const std::string &str) | |
{ | |
int size_needed = MultiByteToWideChar(CP_ACP, 0, &str[0], (int)str.size(), NULL, 0); | |
std::wstring wstrTo(size_needed, 0); | |
MultiByteToWideChar(CP_ACP, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed); | |
return wstrTo; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment