How do I convert between encodings?

C++, encoding, conversion, iconv, character sets
This guide provides an overview of how to convert between different text encodings in C++.

// Example code to convert between UTF-8 and UTF-16 in C++
#include 
#include 
#include 
#include 

std::string utf16_to_utf8(const std::u16string& utf16) {
    std::wstring_convert<:codecvt_utf8_utf16>, char16_t> converter;
    return converter.to_bytes(utf16);
}

std::u16string utf8_to_utf16(const std::string& utf8) {
    std::wstring_convert<:codecvt_utf8_utf16>, char16_t> converter;
    return converter.from_bytes(utf8);
}

int main() {
    std::u16string utf16 = u"Hello, world!";
    std::string utf8 = utf16_to_utf8(utf16);
    std::cout << "UTF-8: " << utf8 << std::endl;

    std::u16string convertedBack = utf8_to_utf16(utf8);
    std::wcout << L"UTF-16: " << convertedBack << std::endl;

    return 0;
}
        

C++ encoding conversion iconv character sets