iconv
is a POSIX function that can take care of the intermediate encoding step. You can use iconv_open
to specify that you have UTF-8 input and that you want UTF-16 output. Then, using the handle returned from iconv_open
, you can use iconv
(specifying your input buffer and output buffer). When you are done you must call iconv_close
on the handle returned from iconv_open
to free resources etc.
You will have to peruse your system's documentation about what encodings are supported by iconv
and their naming scheme (i.e. what to provide iconv_open
). For example, iconv
on some systems expect "utf-8"
and others it may expect "UTF8"
etc.
Windows does not provide a version of iconv, and instead provides it's own UTF formatting functions: MultiByteToWideChar and WideCharToMultiByte.
//UTF8 to UTF16
std::string input = ...
int utf16len = MultiByteToWideChar(CP_UTF8, 0, input.c_str(), input.size(),
NULL, 0);
std::wstring output(utf16len);
MultiByteToWideChar(CP_UTF8, 0, input.c_str(), input.size(),
&output[0], output.size());
//UTF16 to UTF8
std::wstring input = ...
int utf8len = WideCharToMultiByte(CP_UTF8, 0, input.c_str(), input.size(),
NULL, 0, NULL, NULL);
std::string output(utf8len);
WideCharToMultiByte(CP_UTF8, 0, input.c_str(), input.size(),
&output[0], output.size(), NULL, NULL);