Skip to content

Instantly share code, notes, and snippets.

@pixnblox
Last active October 27, 2020 18:41
Show Gist options
  • Save pixnblox/b4980243334a1292bed957493941f071 to your computer and use it in GitHub Desktop.
Save pixnblox/b4980243334a1292bed957493941f071 to your computer and use it in GitHub Desktop.
Convert Between UTF-8 and UTF 16
#include <codecvt>
#include <string>
using namespace std;
// UTF-16 to UTF-8 (variable-width encoding) string conversion.
// NOTE: This will throw a range_error exception if the input is invalid.
inline string narrow(const wstring& utf16Source)
{
wstring_convert<codecvt_utf8_utf16<wchar_t>> converter;
return converter.to_bytes(utf16Source);
}
// UTF-8 to UTF-16 string (variable-width encoding) conversion.
// NOTE: This will throw a range_error exception if the input is invalid.
inline wstring widen(const string& utf8Source)
{
wstring_convert<codecvt_utf8_utf16<wchar_t>> converter;
return converter.from_bytes(utf8Source);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment