Constantin
Constantin

Reputation: 8961

Use iconv API in C

I try to convert a sjis string to utf-8 using the iconv API. I compiled it already succesfully, but the output isn't what I expected. My code:

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

I got only random numbers. Any ideas?

Edit: My input is

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

And output should be: 0x88 0x9F

But is in fact: 0x30 0x00 0x00 0x31 0x00 ...

Upvotes: 0

Views: 2631

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799150

I was unable to duplicate the problem. The only thing I can suggest is to be careful about your allocations.

Code:

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

Output:

$ gcc t.c
$ ./a.out
88
9f

Upvotes: 1

Related Questions