Skip to content

Instantly share code, notes, and snippets.

@superlucky8848
Last active January 3, 2023 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save superlucky8848/893144633f189e5bc233f1a15e4610ed to your computer and use it in GitHub Desktop.
Save superlucky8848/893144633f189e5bc233f1a15e4610ed to your computer and use it in GitHub Desktop.
MFC Convert CString encoding between UTF-8 and UTF-16
static CStringA UTF16_UTF8(const CStringW& utf16)
{
if (utf16.IsEmpty()) return "";
CStringA utf8;
int cc = 0;
if ((cc = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, NULL, 0, 0, 0) - 1) > 0)
{
char * buf = utf8.GetBuffer(cc);
if (buf) WideCharToMultiByte(CP_UTF8, 0, utf16, -1, buf, cc, 0, 0);
utf8.ReleaseBuffer();
}
return utf8;
}
static CStringW UTF8_UTF16(const CStringA& utf8)
{
if (utf8.IsEmpty()) return L"";
CStringW utf16;
int cc = 0;
if ((cc = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0) - 1) > 0)
{
wchar_t *buf = utf16.GetBuffer(cc);
if (buf) MultiByteToWideChar(CP_UTF8, 0, utf8, -1, buf, cc);
utf16.ReleaseBuffer();
}
return utf16;
}
@xiaozhu1337
Copy link

There is no need to do encoding conversion, because CString uses UNICODE to represent strings internally

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment