@hoyt.jerde
Можно воспользоваться функцией MultiByteToWideChar
, которая преобразует массив байтов в строку широких символов, а затем использовать функцию WideCharToMultiByte
, чтобы преобразовать эту строку в строку utf-8. Пример:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include #include std::string utf8_from_bytes(const char* bytes, size_t size) { std::wstring wide_str; // Convert bytes to wide characters int wide_size = MultiByteToWideChar(CP_UTF8, 0, bytes, size, nullptr, 0); wide_str.resize(wide_size); MultiByteToWideChar(CP_UTF8, 0, bytes, size, &wide_str[0], wide_size); // Convert wide characters to utf-8 int utf8_size = WideCharToMultiByte(CP_UTF8, 0, wide_str.c_str(), wide_size, nullptr, 0, nullptr, nullptr); std::string utf8_str; utf8_str.resize(utf8_size); WideCharToMultiByte(CP_UTF8, 0, wide_str.c_str(), wide_size, &utf8_str[0], utf8_size, nullptr, nullptr); return utf8_str; } |
Пример использования:
1 2 |
const char bytes[] = { 0xd0, 0x9f, 0xd1, 0x80, 0xd0, 0xb8, 0xd0, 0xb2, 0xd0, 0xb5, 0xd1, 0x82, 0x20, 0xd1, 0x81, 0xd1, 0x82, 0xd1, 0x80, 0xd0, 0xbe, 0xd0, 0xba, 0xd0, 0xb8 }; std::string utf8_str = utf8_from_bytes(bytes, sizeof(bytes)); |
Здесь используется массив байтов, содержащий строки "Привет" и "строка". Функция utf8_from_bytes
преобразует этот массив в строку utf-8 и возвращает результат в виде std::string
.