천객만래 [千客萬來] (It has an interminable succession of visitors)

[개발/VC++] UTF8Decoding, UTF8Encoding


출처 : 인터넷

멀티바이트 환경에서 변환같음. 

char GetHexChar(LPCTSTR str)
{
 int i,num;
 char c[2];
 if(strlen(str)>2) return 0;
 for(i=0;i<2;i++)
 {
  num=toupper(str[i]) - 0x30;
  if(num<0 || num>9)
  {
   if(num>=0x11 && num<=0x16) num-=7;
   else num=0;
  }
  c[i]=(char)num;
 }
 return c[0]*16+c[1];
}
void ParseEscStr(LPCTSTR src, CString &dst, BOOL bEsc)
{
 int n,i;
 char buff[10];
 CString str;
 n = (int)strlen(src);
 dst.Empty();
 if(bEsc)
 {
  for(i=0;i<n;i++)
  {
   if(src[i]<0 || src[i]==0x20)
   {
    wsprintf(buff,"%c%.2x",'%',(unsigned char)src[i]);
    str=buff; str.MakeUpper();
    dst+=str;
   }
   else
    dst+=src[i];
  }
 }
 else
 {
  i=0;
  while(TRUE)
  {
   if(i>=n) break;
   if(src[i]=='%')
   {
    if(i+3>n) break;
    wsprintf(buff,"%c%c",src[i+1],src[i+2]);
    dst+=GetHexChar(buff);
    i+=3;
   }
   else
   {
    dst+=src[i];
    i++;
   }

  }
 }
}


BOOL UTF8Decoding(LPCTSTR src,CString& dst)
{
 CString str;
 ParseEscStr(src,str,FALSE);
 int len=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,str,-1,NULL,0);
 if(len==0) return FALSE;
 LPWSTR pwStr=new WCHAR[len];
 MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,str,-1,pwStr,len);
 dst=pwStr;
 delete[] pwStr;
 return TRUE;
}
void UTF8Encoding(LPCTSTR src,CString& dst)
{
 CString str=src;
 BSTR bstr=str.AllocSysString();
 int len=WideCharToMultiByte(CP_UTF8,0,bstr,-1,NULL,0,NULL,NULL);
 if(len==0) { dst=src; ::SysFreeString(bstr); return; }
 LPTSTR pStr=new char[len];
 WideCharToMultiByte(CP_UTF8,0,bstr,-1,pStr,len,NULL,NULL);
 ParseEscStr(pStr,dst,TRUE);
 ::SysFreeString(bstr);
 delete[] pStr;
 return;
}




Posted by SB패밀리


/////////////////////////////////////////////////////////////
// base64 인코딩/디코딩 및 제거
// base64.h
K4LIB_BASIC_API unsigned char* base64_encode(const unsigned char *string, int length, int *ret_length);
K4LIB_BASIC_API unsigned char* base64_decode(const unsigned char *string, int length, int *ret_length);
K4LIB_BASIC_API void base64_free(unsigned char* data);

 


/////////////////////////////////////////////////////////////
// base64 인코딩/디코딩 및 제거
// base64.cpp
static char base64_table[] =
{ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', '\0'
};
static char base64_pad = '=';

unsigned char *base64_encode(const unsigned char *string, int length, int *ret_length)
{
    const unsigned char *current = string;
    int i    = 0;
    int    wi    =    0;
    int        nAllocSize    =    ((length + 3 - length
  % 3) * 4 / 3 + 1) * sizeof(char);
    nAllocSize    +=    (nAllocSize/80+1)*2;
    unsigned char *result = new unsigned char[nAllocSize];
 
    while (length > 2)
    { /* keep going until we have less than 24 bits */
        result[i++] = base64_table[current[0] >> 2];
        result[i++] = base64_table[((current[0] & 0x03) <<  4)
   + (current[1] >> 4)];
        result[i++] = base64_table[((current[1] & 0x0f) <<  2)
   + (current[2] >> 6)];
        result[i++] = base64_table[current[2] & 0x3f];
 
        current += 3;
        length -= 3; /* we just handle 3 octets of data */
        wi+=4;
 
/*        if(wi%80 == 0)
        {
            result[i++] = '\r';
            result[i++] = '\n';
        }
*/    }
 
    /* now deal with the tail end of things */
    if (length != 0)
    {
        result[i++] = base64_table[current[0] >> 2];
        if (length > 1)
        {
            result[i++] = base64_table[((current[0] &
    0x03) <<  4) + (current[1] >> 4)];
            result[i++] = base64_table[(current[1] &
    0x0f) <<  2];
            result[i++] = base64_pad;
        }else
        {
            result[i++] = base64_table[(current[0] &
    0x03) <<  4];
            result[i++] = base64_pad;
            result[i++] = base64_pad;
        }
    }
    if(ret_length)
    {
        *ret_length = i;
    }
    result[i] = '\0';
    return result;
}

/* as above, but backwards. :) */
unsigned char *base64_decode(const unsigned char *string, int length, int *ret_length)
{
    const unsigned char *current = string;
    int ch, i = 0, j = 0, k;
    char *chp;
 
    unsigned char *result = new unsigned char[(length / 4 *3 + 1) * sizeof(char)];
    if (result == NULL) {
        return NULL;
    }
 
    /* run through the whole string, converting as we go */
    while ((ch = *current++) != '\0') {
        if (ch == base64_pad) break;
        chp = strchr(base64_table, ch);
        if (chp == NULL) continue;
        ch = chp - base64_table;
 
        switch(i % 4) {
        case 0:
            result[j] = (unsigned char)(ch <<  2);
            break;
        case 1:
            result[j++] |= ch >> 4;
            result[j] = (unsigned char)((ch & 0x0f) <<  4);
            break;
        case 2:
            result[j++] |= ch >>2;
            result[j] = (unsigned char)((ch & 0x03) <<  6);
            break;
        case 3:
            result[j++] |= ch;
            break;
        }
        i++;
    }
 
    k = j;
    /* mop things up if we ended on a boundary */
    if (ch == base64_pad) {
        switch(i % 4) {
        case 0:
        case 1:
            delete [] result;
            return NULL;
        case 2:
            k++;
        case 3:
            result[k++] = 0;
        }
    }
    if(ret_length) {
        *ret_length = j;
    }
    result[k] = '\0';
    return result;
}

void base64_free(unsigned char* data)
{
 delete[] data;
}

Posted by SB패밀리

출처 : 인터넷

멀티바이트 환경에서 변환같음.

char GetHexChar(LPCTSTR str)
{
 int i,num;
 char c[2];
 if(strlen(str)>2) return 0;
 for(i=0;i<2;i++)
 {
  num=toupper(str[i]) - 0x30;
  if(num<0 || num>9)
  {
   if(num>=0x11 && num<=0x16) num-=7;
   else num=0;
  }
  c[i]=(char)num;
 }
 return c[0]*16+c[1];
}
void ParseEscStr(LPCTSTR src, CString &dst, BOOL bEsc)
{
 int n,i;
 char buff[10];
 CString str;
 n = (int)strlen(src);
 dst.Empty();
 if(bEsc)
 {
  for(i=0;i<n;i++)
  {
   if(src[i]<0 || src[i]==0x20)
   {
    wsprintf(buff,"%c%.2x",'%',(unsigned char)src[i]);
    str=buff; str.MakeUpper();
    dst+=str;
   }
   else
    dst+=src[i];
  }
 }
 else
 {
  i=0;
  while(TRUE)
  {
   if(i>=n) break;
   if(src[i]=='%')
   {
    if(i+3>n) break;
    wsprintf(buff,"%c%c",src[i+1],src[i+2]);
    dst+=GetHexChar(buff);
    i+=3;
   }
   else
   {
    dst+=src[i];
    i++;
   }

  }
 }
}


BOOL UTF8Decoding(LPCTSTR src,CString& dst)
{
 CString str;
 ParseEscStr(src,str,FALSE);
 int len=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,str,-1,NULL,0);
 if(len==0) return FALSE;
 LPWSTR pwStr=new WCHAR[len];
 MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,str,-1,pwStr,len);
 dst=pwStr;
 delete[] pwStr;
 return TRUE;
}
void UTF8Encoding(LPCTSTR src,CString& dst)
{
 CString str=src;
 BSTR bstr=str.AllocSysString();
 int len=WideCharToMultiByte(CP_UTF8,0,bstr,-1,NULL,0,NULL,NULL);
 if(len==0) { dst=src; ::SysFreeString(bstr); return; }
 LPTSTR pStr=new char[len];
 WideCharToMultiByte(CP_UTF8,0,bstr,-1,pStr,len,NULL,NULL);
 ParseEscStr(pStr,dst,TRUE);
 ::SysFreeString(bstr);
 delete[] pStr;
 return;
}

Posted by SB패밀리

출처 : http://www.hoonsbara.com/hoonsboard.aspx?table_name=asptip&board_idx=447451&page=4&keyword=&search=&boardmode=2

 protected string Base64Encode(string str)
{
  return Convert.ToBase64String(
    System.Text.Encoding.GetEncoding("euc-kr").GetBytes(str)); 
}

protected string Base64Decode(string str)
{
  return System.Text.Encoding.GetEncoding("euc-kr").GetString(
    System.Convert.FromBase64String(str));
}

void Page_Load(Object src, EventArgs e )
{
  string str="인코딩할 한글 1234567890!@#$%^&*()";
  Response.Write( "인코딩 전 : " + str +"<br>" );
  string encoded = Base64Encode(str);
  Response.Write( "BASE64 인코드 : " + encoded +"<br>");
  string decoded = Base64Decode(encoded);
  Response.Write( "BASE64 디코드 : " + decoded +"<br>");
}

===================================================================================================

 

출처 : MSDN 2003

 

public void EncodeWithString() {
    System.IO.FileStream inFile;    
    byte[]                 binaryData;

    try {
        inFile = new System.IO.FileStream(inputFileName,
                                          System.IO.FileMode.Open,
                                          System.IO.FileAccess.Read);
        binaryData = new Byte[inFile.Length];
        long bytesRead = inFile.Read(binaryData, 0,
                                    (int)inFile.Length);
        inFile.Close();
    }
    catch (System.Exception exp) {
        // Error creating stream or reading from it.
        System.Console.WriteLine("{0}", exp.Message);
        return;
    }

    // Convert the binary input into Base64 UUEncoded output.
    string base64String;
    try {
         base64String =
            System.Convert.ToBase64String(binaryData,
                                          0,
                                          binaryData.Length);
    }
    catch (System.ArgumentNullException) {
        System.Console.WriteLine("Binary data array is null.");
        return;
    }

    // Write the UUEncoded version to the output file.
    System.IO.StreamWriter outFile;
    try {
        outFile = new System.IO.StreamWriter(outputFileName,
                                    false,
                                    System.Text.Encoding.ASCII);            
        outFile.Write(base64String);
        outFile.Close();
    }
    catch (System.Exception exp) {
        // Error creating stream or writing to it.
        System.Console.WriteLine("{0}", exp.Message);
    }
}

 
Posted by SB패밀리