Date: 2007oct16
Platform: win32
Keywords: utf8, utf16, utf32, unicode
Q. Windows: How to convert between UTF-8 and UTF-16 in Windows?
(Sometimes "UTF-16" is simply called "Unicode" in the Windows world)
A. These two functions do the trick:
int Utf8ToUnicode(LPCSTR szIn, LPWSTR szOut, const size_t sizeOut) {
int page = CP_UTF8;
if (IsWindows9x()) page = CP_ACP; // Win95 can't handle UTF-8 so do ANSI
const int cchWideChar = sizeOut / sizeof(WCHAR); // MultiByteToWideChar() expects the number of characters rather than bytes
return ::MultiByteToWideChar(page, 0, szIn, -1, szOut, cchWideChar);
}
int UnicodeToUtf8(LPCWSTR szIn, LPSTR szOut, const size_t sizeOut) {
int page = CP_UTF8;
if (IsWindows9x()) page = CP_ACP;
return ::WideCharToMultiByte(page, 0, szIn, -1, szOut, sizeOut, NULL, NULL);
}
void ExampleUse1() {
CHAR szTxtA[MAX_PATH] = "Some text";
WCHAR szTxtW[MAX_PATH];
Utf8ToUnicode(szTxtA, szTxtW, sizeof(szTxtW));
}
void ExampleUse2() {
WCHAR szTxtW[MAX_PATH] = L"Some text";
CHAR szTxtA[MAX_PATH];
UnicodeToUtf8(szTxtW, szTxtA, sizeof(szTxtA));
}
See other tips for checking if you are using Windows9x.
Or you can simply remove the Windows9x check.