Browse - Programming Tips - How can I convert between UTF-8 and UTF-16 in Windows?

Date: 2007oct16
Platform: win32
Keywords: utf8, utf16, utf32, unicode

Q.  How can I 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 return MultiByteToWideChar(page, 0, szIn, -1, szOut, sizeOut); } 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); }
See other tips for checking if you are using Windows9x.