簡體   English   中英

如何使用 C++ 將 ISO-2022-KR 編碼轉換為 UTF-8 編碼?

[英]How to convert ISO-2022-KR encoding to UTF-8 encoding using C++?

我有這些以 charset="iso-2022-kr" 編碼的字符 (Bw@e)。 這些字符的十六進制值為 28 0E 42 77 40 65 0F 29。

Unix iconv 中有一個 API 可用,它可以將編碼從 iso-2022-kr 轉換為 utf-8。

示例:iconv -f iso-2022-kr -t utf8 輸入 > Output。

轉換為 UTF-8 后,十六進制值為:28 EC B0 A8 EC 9E A5 29 (차장)

如果使用以下鏈接對上述十六進制值 (UTF-8) 進行解碼: https://software.hixie.ch/utilities/cgi/unicode-decoder/utf8-decoder

結果:作為原始字符:

(차장)

我正在尋找 C++ 中的源代碼,它可以將編碼從 iso-2022-kr 轉換為 UTF-8 編碼。 我已經處理了解碼部分,它在 UTF-8 中編碼。 任何幫助,將不勝感激。

這是一個快速而骯臟的 C++ 程序,它演示了如何使用 iconv 庫接口(可能需要與-liconv鏈接):

#include <cstdio>
#include <cstdlib>
#include <iconv.h>

int main() {    
  iconv_t conv = iconv_open("utf-8", "iso-2022-kr");
  if (conv == reinterpret_cast<iconv_t>(-1)) {
    std::perror("iconv_open");
    return EXIT_FAILURE;
  }

  char iso2022kr_buf[] = "\x28\x0E\x42\x77\x40\x65\x0F\x29";
  char utf8_buf[128];
  std::size_t kr_bytes = sizeof iso2022kr_buf - 1;
  std::size_t utf8_bytes = sizeof utf8_buf;    
  char *as_iso2022kr = iso2022kr_buf;
  char *as_utf8 = utf8_buf;

  std::size_t len = iconv(conv, &as_iso2022kr, &kr_bytes, &as_utf8, &utf8_bytes);
  if (len == static_cast<std::size_t>(-1)) {
    std::perror("iconv");
    return EXIT_FAILURE;
  }
  *as_utf8 = '\0';
  for (const char *c = utf8_buf; c != as_utf8; c++) {
    std::printf("%02hhX ", *c);
  }
  std::putchar('\n');

  std::puts(utf8_buf);
  
  iconv_close(conv);
  return 0;
}

在行動:

$ g++ -O -Wall -Wextra iconv_demo.cpp
$ ./a.out
28 EC B0 A8 EC 9E A5 29 
(차장)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM