Skip to content

Instantly share code, notes, and snippets.

@gchudnov
Created November 6, 2014 19:33
Show Gist options
  • Select an option

  • Save gchudnov/c1ba72d45e394180e22f to your computer and use it in GitHub Desktop.

Select an option

Save gchudnov/c1ba72d45e394180e22f to your computer and use it in GitHub Desktop.
C++ string conversion UTF8 <-> UTF16
#include <string>
#include <locale>
#include <codecvt>
//UTF-8 to UTF-16
std::string source;
//...
std::wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t> convert;
std::u16string dest = convert.from_bytes(source);
//UTF-16 to UTF-8
std::u16string source;
//...
std::wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t> convert;
std::string dest = convert.to_bytes(source);
@TheEpicFace007
Copy link
Copy Markdown

thank you so much

@nguyenvanhoangnhan
Copy link
Copy Markdown

thank you a lot,
im tryna convert wstring(utf16) <=> string(utf8), so i did a small fixes on your code.
here is it

// string (utf8) -> u16string -> wstring
wstring utf8_to_utf16(const string& utf8)
{
    wstring_convert<codecvt_utf8_utf16<char16_t>,char16_t> convert; 
    u16string utf16 = convert.from_bytes(utf8);
    wstring wstr(utf16.begin(), utf16.end());
    return wstr;
}
// wstring -> u16string -> string (utf8)
string utf16_to_utf8(const wstring& utf16) {
    u16string u16str(utf16.begin(), utf16.end());
    wstring_convert<codecvt_utf8_utf16<char16_t>,char16_t> convert; 
    string utf8 = convert.to_bytes(u16str);
    return utf8;
}

@GrinlexGH
Copy link
Copy Markdown

codecvt_utf8* with wstring_convert deprecated in C++17, removed in C++26

@snowyu
Copy link
Copy Markdown

snowyu commented Mar 3, 2025

wstring(wchar_t) is utf-32 on linux.

@TheEpicFace007
Copy link
Copy Markdown

It's in the standard library of cpp

@boreals-back-again
Copy link
Copy Markdown

It's in the standard library of cpp

What?

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