Below is a C++ function that converts an std::u16string (UTF-16 encoded) to an std::string (UTF-8 encoded). This implementation is designed to work on Windows, utilizing the Windows APIs for conversion between UTF-16 (used internally by Windows) and UTF-8.
#include <string>
#include <windows.h>
std::string u16string_to_utf8(const std::u16string& u16str) {
// If the input string is empty, return an empty std::string
if (u16str.empty()) {
return std::string();
}
// Convert from UTF-16 to UTF-8 using WideCharToMultiByte
int requiredSize = WideCharToMultiByte(
CP_UTF8, // Code page for UTF-8
0, // Flags (set to 0 for default)
reinterpret_cast<LPCWSTR>(u16str.data()), // Input wide (UTF-16) string
static_cast<int>(u16str.size()), // Length of input string
nullptr, // No output buffer (we're getting size only)
0, // Zero means we want to calculate required size
nullptr, // No default char
nullptr // No default char was used
);
if (requiredSize <= 0) {
throw std::runtime_error("Error during UTF-16 to UTF-8 conversion: failed to calculate size.");
}
// Create a buffer to hold the converted string
std::string utf8str(requiredSize, '\0');
// Perform the actual conversion
int convertedSize = WideCharToMultiByte(
CP_UTF8, // Code page for UTF-8
0, // Flags (set to 0 for default)
reinterpret_cast<LPCWSTR>(u16str.data()), // Input wide (UTF-16) string
static_cast<int>(u16str.size()), // Length of input string
utf8str.data(), // Output buffer for the UTF-8 string
requiredSize, // Size of the output buffer
nullptr, // No default char
nullptr // No default char was used
);
if (convertedSize <= 0) {
throw std::runtime_error("Error during UTF-16 to UTF-8 conversion: conversion failed.");
}
return utf8str;
}
Explanation of the Code:
- Purpose: Converts an
std::u16string (which is a string of UTF-16 code units) to an std::string formatted as UTF-8.
- Windows API Function:
WideCharToMultiByte is used to perform the conversion from UTF-16 to UTF-8.
- The first call calculates the size needed for the UTF-8 encoded buffer.
- The second call actually writes the UTF-8 encoded string into the buffer.
- Error Handling:
- If
WideCharToMultiByte returns 0 during size calculation or conversion, an exception is thrown to indicate a failure.
- Result: The output
std::string contains the UTF-8 encoded version of the input std::u16string.
Example Usage:
#include <iostream>
int main() {
// UTF-16 string (e.g., may contain Unicode characters)
std::u16string utf16_string = u"Hello, 🌍";
try {
// Convert to a UTF-8 encoded std::string
std::string utf8_string = u16string_to_utf8(utf16_string);
// Output the result
std::cout << "Converted UTF-8 string: " << utf8_string << std::endl;
} catch (const std::exception& e) {
std::cerr << "Conversion failed: " << e.what() << std::endl;
}
return 0;
}
Notes:
- The
WideCharToMultiByte function handles surrogate pairs properly, so it can convert Unicode characters beyond the Basic Multilingual Plane (e.g., emoji) correctly.
- Always ensure proper error handling since character encoding issues can lead to runtime errors in some cases.