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

时间:2013-12-06 08:46:36

标签: c++ unicode utf-8

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

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

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

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

还是有其他方法可以直接在文件中写入unicode字符。

8 个答案:

答案 0 :(得分:5)

最后!使用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 == "\xe2\x82\xac");
}

答案 1 :(得分:3)

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

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

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

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

ICU的例子:

#include <iostream>
#include <unicode\ustream.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 ICU\include in your include path
// and ICU\lib(64) in your library path.
#include <iostream>
#include <fstream>
#include <unicode\ustream.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();
}

答案 2 :(得分:2)

以下代码可以帮助您,

#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);
}

答案 3 :(得分:2)

此代码使用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字节的缓冲区2x(对于你的情况,它意味着12 + 1字节) - 它应该总是足够的。

答案 4 :(得分:0)

答案 5 :(得分:0)

使用std c ++

#include <iostream>
#include <locale>
#include <vector>

int main()
{
    typedef std::codecvt<wchar_t, char, mbstate_t> Convert;
    std::wstring w = L"\u20ac\u20ab\u20ac";
    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;
}

答案 6 :(得分:0)

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

答案 7 :(得分:0)

我遇到了类似但略有不同的问题。我将带有 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 = "F\u00f3\u00f3 B\u00e1r";
    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

相关问题