Skip to content

Instantly share code, notes, and snippets.

@superlucky8848
Last active June 15, 2024 10:48
Show Gist options
  • 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

@BuyukBang
Copy link

Thanks you! This helped me toconvert libmaxminddb's utf8 std::string to proper CString.

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