如何在c++中将unicode代码点转换为utf-8

How to convert unicode code points to utf-8 in c++?

本文关键字:转换 utf-8 代码 unicode c++ 中将      更新时间:2023-10-16

我有一个由unicode代码点组成的数组

unsigned short array[3]={0x20ac,0x20ab,0x20ac};

我只想将其转换为utf-8,使用C++逐字节写入文件。

示例:0x20ac应转换为e2 82 ac。

或者有没有其他方法可以直接在文件中写入unicode字符。

终于来了!使用C++11!

#include <string>
#include <locale>
#include <codecvt>
#include <cassert>
int main()
{
    std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;
    std::string u8str = converter.to_bytes(0x20ac);
    assert(u8str == "xe2x82xac");
}

术语Unicode指的是文本编码和处理的标准。这包含了UTF-8UTF-16UTF-32UCS-2等编码。。。

我猜您是在Windows环境中编程的,其中Unicode通常指UTF-16

在C++中使用Unicode时,我建议使用ICU库。

如果您在Windows上编程,不想使用外部库,并且对平台依赖性没有限制,则可以使用WideCharToMultiByte

ICU示例:

#include <iostream>
#include <unicodeustream.h>
using icu::UnicodeString;
int main(int, char**) {
    //
    // Convert from UTF-16 to UTF-8
    //
    std::wstring utf16 = L"foobar";
    UnicodeString str(utf16.c_str());
    std::string utf8;
    str.toUTF8String(utf8);
    std::cout << utf8 << std::endl;
}

做你想做的事:

// Assuming you have ICUinclude in your include path
// and ICUlib(64) in your library path.
#include <iostream>
#include <fstream>
#include <unicodeustream.h>
#pragma comment(lib, "icuio.lib")
#pragma comment(lib, "icuuc.lib")
void writeUtf16ToUtf8File(char const* fileName, wchar_t const* arr, size_t arrSize) {
    UnicodeString str(arr, arrSize);
    std::string utf8;
    str.toUTF8String(utf8);
    std::ofstream out(fileName, std::ofstream::binary);
    out << utf8;
    out.close();
}

以下代码可能会对您有所帮助,

#include <atlconv.h>
#include <atlstr.h>
#define ASSERT ATLASSERT
int main()
{
    const CStringW unicode1 = L"x0391 and x03A9"; // 'Alpha' and 'Omega'
    const CStringA utf8 = CW2A(unicode1, CP_UTF8);
    ASSERT(utf8.GetLength() > unicode1.GetLength());
    const CStringW unicode2 = CA2W(utf8, CP_UTF8);
    ASSERT(unicode1 == unicode2);
}

此代码使用WideCharToMultiByte(我假设您使用的是Windows):

unsigned short wide_str[3] = {0x20ac, 0x20ab, 0x20ac};
int utf8_size = WideCharToMultiByte(CP_UTF8, 0, wide_str, 3, NULL, 0, NULL, NULL) + 1;
char* utf8_str = calloc(utf8_size);
WideCharToMultiByte(CP_UTF8, 0, wide_str, 3, utf8_str, utf8_size, NULL, NULL);

您需要调用两次:第一次是获取输出字节数,第二次是实际转换。如果您知道输出缓冲区的大小,您可以跳过第一次调用。或者,您可以简单地分配比原始+1字节大2倍的缓冲区(在您的情况下,这意味着12+1字节)——它应该总是足够的。

使用std c++

#include <iostream>
#include <locale>
#include <vector>
int main()
{
    typedef std::codecvt<wchar_t, char, mbstate_t> Convert;
    std::wstring w = L"u20acu20abu20ac";
    std::locale locale("en_GB.utf8");
    const Convert& convert = std::use_facet<Convert>(locale);
    std::mbstate_t state;
    const wchar_t* from_ptr;
    char* to_ptr;
    std::vector<char> result(3 * w.size() + 1, 0);
    Convert::result convert_result = convert.out(state,
          w.c_str(), w.c_str() + w.size(), from_ptr,
          result.data(), result.data() + result.size(), to_ptr);
    if (convert_result == Convert::ok)
        std::cout << result.data() << std::endl;
    else std::cout << "Failure: " << convert_result << std::endl;
}

Iconv是一个在许多平台上使用的流行库。

我遇到了一个类似但略有不同的问题。我有一些字符串,其中包含Unicode代码点作为字符串表示。例如:";F\u00f3\u00f3 B\u00e1r";。我需要将字符串代码点转换为它们的Unicode字符。

这是我的C#解决方案

using System.Globalization;
using System.Text.RegularExpressions;
static void Main(string[] args)
{
    Regex CodePoint = new Regex(@"\u(?<UTF32>....)");
    Match Letter;
    string s = "Fu00f3u00f3 Bu00e1r";
    string utf32;
    Letter = CodePoint.Match(s);
    while (Letter.Success)
    {
        utf32 = Letter.Groups[1].Value;
        if (Int32.TryParse(utf32, NumberStyles.HexNumber, CultureInfo.GetCultureInfoByIetfLanguageTag("en-US"), out int HexNum))
            s = s.Replace("\u" + utf32, Char.ConvertFromUtf32(HexNum));
        Letter = Letter.NextMatch();
    }
    Console.WriteLine(s);
}

输出:FóBár