0

我尝试使用 iconv API 将 sjis 字符串转换为 utf-8。我已经成功编译了它,但是输出不是我所期望的。我的代码:

void convertUtf8ToSjis(char* utf8, char* sjis){
  iconv_t icd;
  int index = 0;
  char *p_src, *p_dst;
  size_t n_src, n_dst;
  icd = iconv_open("Shift_JIS", "UTF-8");
  int c;
  p_src = utf8;
  p_dst = sjis;
  n_src = strlen(utf8);
  n_dst = 32; // my sjis string size
  iconv(icd, &p_src, &n_src, &p_dst, &n_dst);
  iconv_close(icd);
}

我只得到随机数。有任何想法吗?

编辑:我的输入是

char utf8[] = "\xe4\xba\x9c";       //亜

输出应该是:0x88 0x9F

但实际上是:0x30 0x00 0x00 0x31 0x00 ...

4

1 回答 1

1

我无法复制问题。我唯一能建议的就是要小心你的分配。

代码:

#include <iconv.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

void convertUtf8ToSjis(char* utf8, char* sjis){
 ...
}

int main(int argc, char *argv[])
{
  char utf8[] = "\xe4\xba\x9c";
  char *sjis;
  sjis = malloc(32);
  convertUtf8ToSjis(utf8, sjis);
  int i;
  for (i = 0; sjis[i]; i++)
  {
    printf("%02x\n", (unsigned char)sjis[i]);
  }
  free(sjis);
}

输出:

$ gcc t.c
$ ./a.out
88
9f
于 2010-12-24T04:01:22.610 回答