2010년 1월 19일 화요일

Char to UTF-8

static char *make_utf8_string(const wchar_t *unicode)
{
    int out_size = 0,size = 0, index = 0, out_index = 0;
    unsigned char *out;
 char *out_txt;
  
 unsigned short c;
 char buf[512];

    /* first calculate the size of the target string */
    c = unicode[index++];
    while(c) {
        if(c < 0x0080) {
            size += 1;
   out_size += 3;
        } else if(c < 0x0800) {
            size += 2;
   out_size += 6;
        } else {
            size += 3;
   out_size += 9;
        }
        c = unicode[index++];
    }

    out = (unsigned char*)malloc(size + 1);
    if (out == NULL)
        return NULL;

 out_txt = (char*)malloc(out_size +1);
 memset(out_txt,0,out_size+1);

    index = 0;

    c = unicode[index++];
    while(c)
    {
        if(c < 0x080) {
            out[out_index++] = (unsigned char)c;
   if(c== ' ') // 스페이스 바
    sprintf(buf,"%%%X",(unsigned char)c);
   else if(c == '%')
    sprintf(buf,"%%%c%c",unicode[index++],unicode[index++]);
   else
    sprintf(buf,"%c",(unsigned char)c);
   strcat(out_txt,buf);

        } else if(c < 0x800) {
            out[out_index++] = 0xc0 | (c >> 6);
            out[out_index++] = 0x80 | (c & 0x3f);
  
  
   sprintf(buf,"%%%X", (unsigned char)0xc0 | (c >> 6) );
   strcat(out_txt,buf);
   sprintf(buf,"%%%X", (unsigned char)0x80 | (c & 0x3f) );
   strcat(out_txt,buf);
  
        } else {
            out[out_index++] = 0xe0 | (c >> 12);
            out[out_index++] = 0x80 | ((c >> 6) & 0x3f);
            out[out_index++] = 0x80 | (c & 0x3f);
  
   sprintf(buf,"%%%X", (unsigned char)0xe0 | (c >> 12));
   strcat(out_txt,buf);
   sprintf(buf,"%%%X", (unsigned char)0x80 |((c >> 6) & 0x3f));
   strcat(out_txt,buf);
   sprintf(buf,"%%%X", (unsigned char)0x80 | (c & 0x3f));
   strcat(out_txt,buf);
  
        }
        c = unicode[index++];
    }
    out[out_index] = 0x00;
 free(out); // 값만 저장한 배열..현재는 txt형태로 출력되므로 일단 지워준다..
    //free(out_txt);
 return out_txt;
}

댓글 없음:

댓글 쓰기