2010년 1월 19일 화요일

ANSI to UINICODE and UNICODE to ANISI

Visual C++에서 유니코드 문자열은 BSTR이란 타입으로 표시됩니다. 또 유니코드와 ANSI 문자열간의 변환을 위해서 윈도우 시스템에는 MultiByteToWideChar와 WideCharToMultiByte라는 API가 존재합니다. MFC에서의 BSTR 타입 변환방법이나 ATL로 하는 BSTR 타입 변환도 참고하시기 바랍니다.


ANSI 문자열에서 유니코드로의 변환 방법
// sTime이란 ANSI 문자열을 bstr이란 이름의 유니코드(BSTR 타입) 변수로 변환
char sTime[] = "유니코드 변환 예제";
BSTR bstr;
// sTime을 유니코드로 변환하기에 앞서 먼저 그 길이를 알아야 한다.
int nLen = MultiByteToWideChar(CP_ACP, 0, sTime, lstrlen(sTime), NULL, NULL);
// 얻어낸 길이만큼 메모리를 할당한다.
bstr = SysAllocStringLen(NULL, nLen);
// 이제 변환을 수행한다.
MultiByteToWideChar(CP_ACP, 0, sTime, lstrlen(sTime), bstr, nLen);
         // 필요없어지면 제거한다.
         SysFreeString(bstr);

유니코드에서 ANSI 문자열로의 변환 방법
// newVal이란 BSTR 타입에 있는 유니코드 문자열을 sTime이라는 ANSI 문자열로 변환
char *sTime;
         int nLen = WideCharToMultiByte(CP_ACP, 0, newVal, -1, sTime, 0, NULL, NULL);
         sTime = malloc(nLen+1);
WideCharToMultiByte(CP_ACP, 0, newVal, -1, sTime, 128, NULL, NULL);
        // 필요없으면 메모리를 제거한다.
        free(sTime);

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

UTF-8 to ANSI Char* 변환


#include "stdio.h"
#include "stdlib.h"
#include "conio.h"
#include "windows.h"
static wchar_t *make_unicode_string(const unsigned char *utf8)
{
int size = 0, index = 0, out_index = 0;
wchar_t *out;
unsigned char c;
/* first calculate the size of the target string */
c = utf8[index++];
while(c) {
if((c & 0x80) == 0) {
index += 0;
} else if((c & 0xe0) == 0xe0) {
index += 2;
} else {
index += 1;
}
size += 1;
c = utf8[index++];
}  

out = (wchar_t*)malloc((size + 1) * sizeof(wchar_t));
if (out == NULL)
return NULL;
index = 0;

c = utf8[index++];
while(c)
{
if((c & 0x80) == 0) {
out[out_index++] = c;
} else if((c & 0xe0) == 0xe0) {
out[out_index] = (c & 0x1F) << 12;
            c = utf8[index++];
            out[out_index] |= (c & 0x3F) << 6;
            c = utf8[index++];
            out[out_index++] |= (c & 0x3F);
        } else {
            out[out_index] = (c & 0x3F) << 6;
            c = utf8[index++];
            out[out_index++] |= (c & 0x3F);
        }
        c = utf8[index++];
    }
    out[out_index] = 0;

    return out;
}


int utf8_decode(const char *from, char **to)
{
    wchar_t *unicode;
    int chars, err;
    /* On NT-based windows systems, we could use MultiByteToWideChar(CP_UTF8), but
     * MS doesn't actually have a consistent API across win32.
     */
    unicode = make_unicode_string((const unsigned char*)from);
    if(unicode == NULL)
    {
        fprintf(stderr, "Out of memory processing string from UTF8 to UNICODE16\n");
        return -1;
    }

    chars = WideCharToMultiByte(GetConsoleCP(), WC_COMPOSITECHECK, unicode,
            -1, NULL, 0, NULL, NULL);

    if(chars == 0)
    {
        fprintf(stderr, "Unicode translation error %d\n", GetLastError());
        free(unicode);
        return -1;
    }

    *to = (char*)calloc(chars + 1, sizeof(unsigned char));
    if(*to == NULL)
    {
        fprintf(stderr, "Out of memory processing string to local charset\n");
        free(unicode);
        return -1;
    }

    err = WideCharToMultiByte(GetConsoleCP(), WC_COMPOSITECHECK, unicode,
            -1, *to, chars, NULL, NULL);
    if(err != chars)
    {
        fprintf(stderr, "Unicode translation error %d\n", GetLastError());
        free(unicode);
        free(*to);
        *to = NULL;
        return -1;
    }
    free(unicode);
    return 0;
}

char* UTF8ToANSI(char *pszCode)
{
    BSTR    bstrWide;
    char*   pszAnsi;
    int     nLength;

    // Get nLength of the Wide Char buffer
    nLength = MultiByteToWideChar(CP_UTF8, 0, pszCode, lstrlen(pszCode) + 1,
                                  NULL, NULL);

    bstrWide = SysAllocStringLen(NULL, nLength);

   // Change UTF-8 to Unicode (UTF-16)
    MultiByteToWideChar(CP_UTF8, 0, pszCode, lstrlen(pszCode) + 1, bstrWide,
                       nLength);

    // Get nLength of the multi byte buffer
    nLength = WideCharToMultiByte(CP_ACP, 0, bstrWide, -1, NULL, 0, NULL, NULL);

    pszAnsi = new char[nLength];

    // Change from unicode to mult byte
    WideCharToMultiByte(CP_ACP, 0, bstrWide, -1, pszAnsi, nLength, NULL, NULL);
    SysFreeString(bstrWide);

    return pszAnsi;
}

main()
{
    FILE *fp;
    char str[80];
    char *str2;
    fp=fopen("data.txt","r");
    fscanf(fp,"%[^\n]",str);
//    utf8_decode(str,&str2);
    str2=UTF8ToANSI(str);
    printf("%s\n",str2);
    getch();
}


Link with oleaut32.lib.

[출처] UTF8 --> char* 변환|작성자 난뽀다