0

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 ...

Constantin
  • 8,721
  • 13
  • 75
  • 126

1 Answers1

1

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
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • It's great to know, that there's no mistake in my function itself. I will check all allocations and search the problem there - thank you very much and have a great christmas! – Constantin Dec 24 '10 at 04:13
  • Hello Constantin.. This code is working fine if the UTF-8 string doesn't have spaces. But when i tested with spaces in between the characters, it does not converting the next characters which are there after the spaces. – uday Oct 04 '12 at 06:23