Base64Encode编码函数(另一个)

来源:互联网 发布:财务结算中心知乎 编辑:程序博客网 时间:2024/06/02 07:31

  昨天测试程序时发现 我的Base64Encode编码函数对, 返回值只8位,今天有搞了一个,完全正确.

CString CSMTP::Base64encode( CString in_str )
{
   const CString _base64_encode_chars=
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
   CString out_str;

   unsigned char c1, c2, c3;
   int i = 0;
   int len = in_str.GetLength();
  
   while ( i<len )
   {
    // read the first byte
    c1 = in_str[i++];
    if ( i==len )       // pad with "="
    {
     out_str += _base64_encode_chars[ c1>>2 ];
     out_str += _base64_encode_chars[ (c1&0x3)<<4 ];
     out_str += "==";
     break;
    }
   
    // read the second byte
    c2 = in_str[i++];
    if ( i==len )       // pad with "="
    {
     out_str += _base64_encode_chars[ c1>>2 ];
     out_str += _base64_encode_chars[ ((c1&0x3)<<4) | ((c2&0xF0)>>4) ];
     out_str += _base64_encode_chars[ (c2&0xF)<<2 ];
     out_str += "=";
     break;
    }
   
    // read the third byte
    c3 = in_str[i++];
    // convert into four bytes string
    out_str += _base64_encode_chars[ c1>>2 ];
    out_str += _base64_encode_chars[ ((c1&0x3)<<4) | ((c2&0xF0)>>4) ];
    out_str += _base64_encode_chars[ ((c2&0xF)<<2) | ((c3&0xC0)>>6) ];
    out_str += _base64_encode_chars[ c3&0x3F ];
   }
  
   return out_str;


}

原创粉丝点击