Base64编码解码类

C++ 图片、文件转base64编码 不要用这个版本https://github.com/hopzebordah/base64encoder/blob/master/encode.cpp有坑,会死在result[i] = '='; 可以用这个版本https://blog.youkuaiyun.com/qq_31681017/article/details/93161285亲测好用 #include "stdafx.h" #include <Windows.h> #include <iostream> #include &.. 阅读详情

// Base64.h: interface for the CBase64 class.
/**///////////////////////////////////////////////////////////////////////

#if !defined(AFX_BASE64_H__FD6A25D1_EE0E_11D1_870E_444553540001__INCLUDED_)
#define AFX_BASE64_H__FD6A25D1_EE0E_11D1_870E_444553540001__INCLUDED_

#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000

#include "MIMECode.h"

// CBase64
// An encoding agent that handles Base64
//
class CBase64 : public CMIMECode
...{
public:
    CBase64();
    virtual ~CBase64();

// Override the base class mandatory functions
    virtual int Decode( LPCTSTR szDecoding, LPTSTR szOutput );
    virtual CString Encode( LPCTSTR szEncoding, int nSize );

protected:
    void write_bits( UINT nBits, int nNumBts, LPTSTR szOutput, int& lp );
    UINT read_bits( int nNumBits, int* pBitsRead, int& lp );

    int m_nInputSize;
    int m_nBitsRemaining;
    ULONG m_lBitStorage;
    LPCTSTR m_szInput;

    static int m_nMask[];
    static CString m_sBase64Alphabet;
private:
};

CString Base64String(CString str,CString Charset = "gb2312" );

#endif // !defined(AFX_BASE64_H__FD6A25D1_EE0E_11D1_870E_444553540001__INCLUDED_)






// Base64.cpp: implementation of the CBase64 class.
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "Base64.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

// Static Member Initializers
//

// The 7-bit alphabet used to encode binary information
CString CBase64::m_sBase64Alphabet =
_T( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" );

int CBase64::m_nMask[] = { 0, 1, 3, 7, 15, 31, 63, 127, 255 };

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CBase64::CBase64()
{

     m_nInputSize=0;
     m_nBitsRemaining=0;
     m_lBitStorage=0;
}

CBase64::~CBase64()
{
}

CString Base64String(CString str, CString Charset)
{
    //"“From: =?gb2312?B?us7TsQ==?= <hy@ipiinfo.com>”"
    CBase64 code;
    CString strok=code.Encode(str,str.GetLength());
    CString rt;
    rt.Format("=?%s?B?%s==?=",Charset,strok);
  
    return rt;

}


CString CBase64::Encode(LPCTSTR szEncoding, int nSize)
{
    CString sOutput = _T( "" );
    int nNumBits = 6;
    UINT nDigit;
    int lp = 0;

    ASSERT( szEncoding != NULL );
    if( szEncoding == NULL )
        return sOutput;
    m_szInput = szEncoding;
    m_nInputSize = nSize;

    m_nBitsRemaining = 0;
    nDigit = read_bits( nNumBits, &nNumBits, lp );
    while( nNumBits > 0 )
    {
        sOutput += m_sBase64Alphabet[ (int)nDigit ];
        if((sOutput.GetLength()-76) % 78 == 0)
            sOutput+=" ";
        nDigit = read_bits( nNumBits, &nNumBits, lp );
    }
    // Pad with '=' as per RFC 1521
    while( sOutput.GetLength() % 4 != 0 )
    {
        sOutput += '=';
    }
    return sOutput;
}

// The size of the output buffer must not be less than
// 3/4 the size of the input buffer. For simplicity,
// make them the same size.
int CBase64::Decode(LPCTSTR szDecoding, LPTSTR szOutput)
{
    CString sInput;
    int c, lp =0;
    int nDigit;
    int nDecode[ 256 ];

    ASSERT( szDecoding != NULL );
    ASSERT( szOutput != NULL );
    if( szOutput == NULL )
        return 0;
    if( szDecoding == NULL )
        return 0;
    sInput = szDecoding;
    if( sInput.GetLength() == 0 )
        return 0;

    // Build Decode Table
    //
    for( int i = 0; i < 256; i++ )
        nDecode[i] = -2; // Illegal digit
  
    for( i=0; i < 64; i++ )
    {
        nDecode[ m_sBase64Alphabet[ i ] ] = i;
        nDecode[ m_sBase64Alphabet[ i ] | 0x80 ] = i; // Ignore 8th bit
        nDecode[ '=' ] = -1;
        nDecode[ '=' | 0x80 ] = -1; // Ignore MIME padding char
    }

    // Clear the output buffer
    memset( szOutput, 0, sInput.GetLength() + 1 );

    // Decode the Input
    //
    for( lp = 0, i = 0; lp < sInput.GetLength(); lp++ )
    {
        c = sInput[ lp ];
        nDigit = nDecode[ c & 0x7F ];
        if( nDigit < -1 )
        {
            return i;
        }
        else if( nDigit >= 0 )
            // i (index into output) is incremented by write_bits()
            write_bits( nDigit & 0x3F, 6, szOutput, i );
    }  
    return i;
}




UINT CBase64::read_bits(int nNumBits, int * pBitsRead, int& lp)
{
    ULONG lScratch;
    while( ( m_nBitsRemaining < nNumBits ) &&
           ( lp < m_nInputSize ) )
    {
        int c = m_szInput[ lp++ ];
        m_lBitStorage <<= 8;
        m_lBitStorage |= (c & 0xff);
        m_nBitsRemaining += 8;
    }
    if( m_nBitsRemaining < nNumBits )
    {
        lScratch = m_lBitStorage << ( nNumBits - m_nBitsRemaining );
        *pBitsRead = m_nBitsRemaining;
        m_nBitsRemaining = 0;
    }
    else
    {
        lScratch = m_lBitStorage >> ( m_nBitsRemaining - nNumBits );
        *pBitsRead = nNumBits;
        m_nBitsRemaining -= nNumBits;
    }
    return (UINT)lScratch & m_nMask[nNumBits];
}


void CBase64::write_bits(UINT nBits,
                         int nNumBits,
                         LPTSTR szOutput,
                         int& i)
{
    UINT nScratch;

    m_lBitStorage = (m_lBitStorage << nNumBits) | nBits;
    m_nBitsRemaining += nNumBits;
    while( m_nBitsRemaining > 7 )
    {
        nScratch = m_lBitStorage >> (m_nBitsRemaining - 8);
        szOutput[ i++ ] = nScratch & 0xFF;
        m_nBitsRemaining -= 8;
    }
} 

 

(原创)昨天为了测试我的终端,自己写了个模拟服务器,用到BASE64 编解码,已用了GoAhead的代码,发现不支持中文,自己改造一下,解决了问题。现在把代码发上来给大家借鉴。


/*
* base64.c -- Base64 Mime encoding
*
* Copyright (c) GoAhead Software Inc., 1995-2000. All Rights Reserved.
*
* See the file "license.txt" for usage and redistribution license requirements
*
* $Id: base64.c,v 1.1 2005/08/12 06:50:14 archfree Exp $
*/

/******************************** Description *********************************/

/*
* The base64 command encodes and decodes a string in mime base64 format
*/


/******************************** Local Data **********************************/
/*
* Mapping of ANSI chars to base64 Mime encoding alphabet (see below)
*/

#if 0
static char map64[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
};
#endif
static char map64[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, 0, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1,
-1, -1,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1};

static char alphabet64[] = {
'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', '+', '/',
};

/*********************************** Code *************************************/
/*
* Decode a buffer from "string" and into "outbuf"
*/

int websDecode64(char *outbuf, char *string, int outlen)
{
unsigned long shiftbuf;
char *cp, *op;
int c, i, j, shift;

op = outbuf;
*op = '/0';
cp = string;
while (*cp && *cp != '=') {
/*
* Map 4 (6bit) input bytes and store in a single long (shiftbuf)
*/
shiftbuf = 0;
shift = 18;
for (i = 0; i < 4 && *cp && *cp != '='; i++, cp++) {
c = map64[*cp & 0xff];
if (c == -1) {
#if zwhtemp
error(E_L, E_LOG, T("Bad string: %s at %c index %d"), string,
c, i);
#endif
return -1;
}
shiftbuf = shiftbuf | (c << shift);
shift -= 6;
}
/*
* Interpret as 3 normal 8 bit bytes (fill in reverse order).
* Check for potential buffer overflow before filling.
*/
--i;
if ((op + i) >= &outbuf[outlen]) {
//gstrcpy(outbuf, T("String too big"));]
//strcpy(outbuf, T("String too big"));
strcpy(outbuf, "String too big");

return -1;
}
for (j = 0; j < i; j++) {
*op++ = (char) ((shiftbuf >> (8 * (2 - j))) & 0xff);
}
*op = '/0';
}
return 0;
}


/******************************************************************************/
/*
* Encode a buffer from "string" into "outbuf"
*/

void websEncode64(char *outbuf, char *string, int outlen)
{
unsigned long shiftbuf;
char *cp, *op;
int x, i, j, shift;

op = outbuf;
*op = '/0';
cp = string;
while (*cp) {
/*
* Take three characters and create a 24 bit number in shiftbuf
*/
shiftbuf = 0;
for (j = 2; j >= 0 && *cp; j--, cp++) {
shiftbuf |= ((*cp & 0xff) << (j * 8));
}
/*
* Now convert shiftbuf to 4 base64 letters. The i,j magic calculates
* how many letters need to be output.
*/
shift = 18;
for (i = ++j; i < 4 && op < &outbuf[outlen] ; i++) {
x = (shiftbuf >> shift) & 0x3f;
*op++ = alphabet64[(shiftbuf >> shift) & 0x3f];
shift -= 6;
}
/*
* Pad at the end with '='
*/
while (j-- > 0) {
*op++ = '=';
}
*op = '/0';
}
}


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

// Base64.h: interface for the Base64 class.
//
//////////////////////////////////////////////////////////////////////

#if !defined(AFX_BASE64_H__D1CE45BE_2DDD_47A2_9777_CA3BA8A42AE4__INCLUDED_)
#define AFX_BASE64_H__D1CE45BE_2DDD_47A2_9777_CA3BA8A42AE4__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include <afx.h>

class Base64
{
public:

 // 将ANSI字符串转成Base64字符串
 static CString encode(const CString in_str);
 static void encode(LPSTR pIn, DWORD dwInLen, LPSTR pOut, LPDWORD pdwOutLen);
 
 // 将Base64字符串转成ANSI字符串
 static CString decode(const CString in_str);
 static void decode(LPSTR pIn, DWORD dwInLen, LPSTR pOut, LPDWORD pdwOutLen);

 // 将ANSI格式文件转成Base64格式文件
 static BOOL encode(const CString cstrSrc, const CString cstrDes);
 static BOOL encodeMemMap(LPCTSTR fIn, LPCTSTR fOut);

 // 将Base64格式文件转成ANSI格式文件
 static BOOL decode(const CString cstrSrc, const CString cstrDes);
 static BOOL decodeMemMap(LPCTSTR fIn, LPCTSTR fOut);

 static inline PSTR AllocMemBase64(DWORD dwANSILen);
 static inline PSTR AllocMemANSI(DWORD dwBase64Len);
 static inline void FreeMemBase64(PSTR pBase64);
 static inline void FreeMemANSI(PSTR pANSI);
 
protected:
 static inline DWORD CalcANSItoBase64Len(DWORD dwANSILen);
 static inline DWORD CalcBase64toANSILen(DWORD dwBase64Len, const CString strBase64End2 = "");

private:

    // encode table(编码表)
    const static CString _base64_encode_chars;
 
    // decode table(解码表)
    const static char _base64_decode_chars[128];


};


//////////////////////////////////////////////////////////////////////////
// 函数:    DWORD CalcANSItoBase64Len()
// 功能:    计算ANSI字符串转成Base64字符串需要多少内存
// 参数:    dwANSILen ANSI字符串的长度
// 返回值:  DWORD Base64字符串的长度
// 日期:    [6/23/2005]
//////////////////////////////////////////////////////////////////////////
inline DWORD Base64::CalcANSItoBase64Len(DWORD dwANSILen)
{
 return (dwANSILen%3) ? (dwANSILen+3)/3*4 : dwANSILen/3*4;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    DWORD CalcBase64toANSILen()
// 功能:    计算Base64字符串转成ANSI字符串需要多少内存
// 参数:    dwANSILen Base64字符串的长度
//   strBase64End2 Base64字符串结尾的二个字符串
// 返回值:  DWORD ANSI字符串的长度
// 日期:    [6/23/2005]
//////////////////////////////////////////////////////////////////////////
inline DWORD Base64::CalcBase64toANSILen(DWORD dwBase64Len, const CString strBase64End2)
{
 //计算'='出现的次数,
 int count = 0;
 for (int i=0; i<strBase64End2.GetLength(); i++)
  if (strBase64End2[i] == '=')
   count ++;

 DWORD dwANSILen = (dwBase64Len%4) ? (dwBase64Len+4)/4*3 : dwBase64Len/4*3;
 dwANSILen -= count;
 return dwANSILen;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    PSTR AllocMemBase64()
// 功能:    分配Base64字符串所需要的空间,这个内存需要用户手动删除
// 参数:    dwANSILen ANSI字符串的长度
// 返回值:  PSTR Base64内存地址
// 日期:    [6/23/2005]
//////////////////////////////////////////////////////////////////////////
inline PSTR Base64::AllocMemBase64(DWORD dwANSILen)
{
 int len = Base64::CalcANSItoBase64Len(dwANSILen);
 char* pBase64 = new char[len+1];
 ZeroMemory(pBase64, len+1);
 
 return pBase64;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    PSTR AllocMemANSI()
// 功能:    分配Base64字符串所需要的空间,这个内存需要用户手动删除
// 参数:    dwANSILen ANSI字符串的长度
// 返回值:  PSTR Base64内存地址
// 日期:    [6/23/2005]
//////////////////////////////////////////////////////////////////////////
inline PSTR Base64::AllocMemANSI(DWORD dwBase64Len)
{
 int len = Base64::CalcBase64toANSILen(dwBase64Len);
 char* pANSI = new char[len+1];
 ZeroMemory(pANSI, len+1);
 
 return pANSI;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    void FreeMemBase64()
// 功能:    删除用AllocMemBase64分配的内存
// 参数:    pBase64 分配内在的地址
// 返回值:  void
// 日期:    [6/25/2005]
//////////////////////////////////////////////////////////////////////////
inline void Base64::FreeMemBase64(PSTR pBase64)
{
 ASSERT(pBase64);
 delete[] pBase64;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    void FreeMemANSI()
// 功能:    删除用AllocMemANSI分配的内存
// 参数:    pANSI 分配内在的地址
// 返回值:  void
// 日期:    [6/25/2005]
//////////////////////////////////////////////////////////////////////////
inline void Base64::FreeMemANSI(PSTR pANSI)
{
 ASSERT(pANSI);
 delete[] pANSI;
}


#endif // !defined(AFX_BASE64_H__D1CE45BE_2DDD_47A2_9777_CA3BA8A42AE4__INCLUDED_)


// Base64.cpp: implementation of the Base64 class.
//
// 作者:王军
//
// 用途:Base64的编码与解码
//
// 创建日期:2004-06-08

//////////////////////////////////////////////////////////////////////
#include "Base64.h"
#include <windows.h>

// 用于编码的字符
const CString Base64::_base64_encode_chars =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

// 用于解码的字符
const char Base64::_base64_decode_chars[] =
{
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
    -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
    -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1
};


//////////////////////////////////////////////////////////////////////////
// 函数:    CString encode()
// 功能:    将ANSI字符串转成Base64字符串
// 参数:    in_str ANSI字符串
// 返回值:  CString Base64字符串
// 日期:    [6/23/2005]
//////////////////////////////////////////////////////////////////////////
CString Base64::encode(const CString in_str)
{
    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;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    CString decode()
// 功能:    将Base64字符串转成ANSI字符串
// 参数:    in_str Base64字符串
// 返回值:  CString ANSI字符串
// 日期:    [6/23/2005]
//////////////////////////////////////////////////////////////////////////
CString Base64::decode(const CString in_str)
{
    CString out_str;
    char c1, c2, c3, c4;
    int i = 0;
    int len = in_str.GetLength();
 
    while ( i<len)
    {
        // read the first byte
        do {
            c1 = _base64_decode_chars[ in_str[i++] ];
        } while ( i<len && c1==-1);

        if ( c1==-1)
            break;

        // read the second byte
        do {
            c2 = _base64_decode_chars[ in_str[i++] ];
        } while ( i<len && c2==-1);

        if ( c2==-1 )
            break;

        // assamble the first byte
        out_str += char( (c1<<2) | ((c2&0x30)>>4) );

        // read the third byte
        do {
            c3 = in_str[i++];
            if ( c3==61 )       // meet with "=", break
                return out_str;
            c3 = _base64_decode_chars[ c3 ];
        } while ( i<len && c3==-1);

        if ( c3==-1 )
            break;

        // assamble the second byte
        out_str += char( ((c2&0XF)<<4) | ((c3&0x3C)>>2) );

        // read the fourth byte
        do {
            c4 = in_str[i++];
            if ( c4==61 )       // meet with "=", break
                return out_str;
            c4 = _base64_decode_chars[ c4 ];
        } while ( i<len && c4==-1 );

        if ( c4==-1 )
            break;

        // assamble the third byte
        out_str += char( ((c3&0x03)<<6) | c4 );
    }

    return out_str;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    void encode()
// 功能:    将ANSI字符串转成Base64字符串
// 参数:    pIn  ANSI字符串
//   dwInLen ANSI字符串的长度
//   pOut 放Base64字符串的内存
//   pdwOutLen Base64字符串的长度
// 返回值:  void
// 日期:    [6/24/2005]
//////////////////////////////////////////////////////////////////////////
void Base64::encode(LPSTR pIn, DWORD dwInLen, LPSTR pOut, LPDWORD pdwOutLen)
{
    unsigned char c1, c2, c3;
    int i = 0, n = 0;
    int len = dwInLen;

    while ( i<len )
    {
        // read the first byte
        c1 = pIn[i++];
        if ( i==len )       // pad with "="
        {
            pOut[n++] = _base64_encode_chars[ c1>>2 ];
            pOut[n++] = _base64_encode_chars[ (c1&0x3)<<4 ];
            pOut[n++] = '=';
            pOut[n++] = '=';
           break;
        }

        // read the second byte
        c2 = pIn[i++];
        if ( i==len )       // pad with "="
        {
            pOut[n++] = _base64_encode_chars[ c1>>2 ];
            pOut[n++] = _base64_encode_chars[ ((c1&0x3)<<4) | ((c2&0xF0)>>4) ];
            pOut[n++] = _base64_encode_chars[ (c2&0xF)<<2 ];
            pOut[n++] = '=';
            break;
        }

        // read the third byte
        c3 = pIn[i++];
        // convert into four bytes string
        pOut[n++] = _base64_encode_chars[ c1>>2 ];
        pOut[n++] = _base64_encode_chars[ ((c1&0x3)<<4) | ((c2&0xF0)>>4) ];
        pOut[n++] = _base64_encode_chars[ ((c2&0xF)<<2) | ((c3&0xC0)>>6) ];
        pOut[n++] = _base64_encode_chars[ c3&0x3F ];
    }
 *pdwOutLen = n;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    void decode()
// 功能:    将Base64字符串转成ANSI字符串
// 参数:    pIn  Base64字符串
//   dwInLen Base64字符串的长度
//   pOut 放ANSI字符串的内存
//   pdwOutLen ANSI字符串的长度
// 返回值:  void
// 日期:    [6/24/2005]
//////////////////////////////////////////////////////////////////////////
void Base64::decode(LPSTR pIn, DWORD dwInLen, LPSTR pOut, LPDWORD pdwOutLen)
{
    char c1, c2, c3, c4;
    int i = 0, n = 0;
    int len = dwInLen;

    while ( i<len)
    {
        // read the first byte
        do {
            c1 = _base64_decode_chars[ pIn[i++] ];
        } while ( i<len && c1==-1);

        if ( c1==-1)
            break;

        // read the second byte
        do {
            c2 = _base64_decode_chars[ pIn[i++] ];
        } while ( i<len && c2==-1);

        if ( c2==-1 )
            break;

        // assamble the first byte
        pOut[n++] = char( (c1<<2) | ((c2&0x30)>>4) );

        // read the third byte
        do {
            c3 = pIn[i++];
            if ( c3==61 )       // meet with "=", break
                goto end; //return;
            c3 = _base64_decode_chars[ c3 ];
        } while ( i<len && c3==-1);

        if ( c3==-1 )
            break;

        // assamble the second byte
        pOut[n++] = char( ((c2&0XF)<<4) | ((c3&0x3C)>>2) );

        // read the fourth byte
        do {
            c4 = pIn[i++];
            if ( c4==61 )       // meet with "=", break
                goto end; //return;
            c4 = _base64_decode_chars[ c4 ];
        } while ( i<len && c4==-1 );

        if ( c4==-1 )
            break;

        // assamble the third byte
        pOut[n++] = char( ((c3&0x03)<<6) | c4 );
    }
end:
 *pdwOutLen = n;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    BOOL encodeMemMap()
// 功能:    将ANSI格式文件转成Base64格式文件
// 参数:    fIn  ANSI格式的文件名
//   fOut Base64格式的文件名
// 返回值:  BOOL TRUE(成功) FALSE(失败)
// 日期:    [6/24/2005]
//////////////////////////////////////////////////////////////////////////
BOOL Base64::encodeMemMap(LPCTSTR fIn, LPCTSTR fOut)
{
 HANDLE hIn, hOut, hInMap, hOutMap;
 LPSTR pIn, pInFile;
 LPSTR pOut, pOutFile;
 DWORD dwInLow, dwOutLow;
 DWORD dwOutLen = 0;

 hIn = CreateFile(fIn, GENERIC_READ, 0, NULL,
  OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
 hInMap = CreateFileMapping(hIn, NULL, PAGE_READONLY,
  0, 0, NULL);
 pInFile = (LPSTR)MapViewOfFile(hInMap, FILE_MAP_READ, 0, 0, 0);
 
 hOut = CreateFile(fOut, GENERIC_READ|GENERIC_WRITE, 0, NULL,
  CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
 dwInLow = GetFileSize(hIn, NULL);
 dwOutLow = CalcANSItoBase64Len(dwInLow);
 hOutMap = CreateFileMapping(hOut, NULL, PAGE_READWRITE,
  0, dwOutLow, NULL);
 pOutFile = (LPSTR)MapViewOfFile(hOutMap, FILE_MAP_WRITE, 0, 0, dwOutLow);

 //转换
 pIn = pInFile;
 pOut = pOutFile;
 encode(pIn, dwInLow, pOut, &dwOutLen);

 UnmapViewOfFile(pOutFile); UnmapViewOfFile(pInFile);
 CloseHandle(hOutMap); CloseHandle(hInMap);
 CloseHandle(hOut); CloseHandle(hIn);
 return TRUE;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    BOOL decodeMemMap()
// 功能:    将Base64格式文件转成ANSI格式文件
// 参数:    fIn  Base64格式的文件名
//   fOut ANSI格式的文件名
// 返回值:  BOOL TRUE(成功) FALSE(失败)
// 日期:    [6/24/2005]
//////////////////////////////////////////////////////////////////////////
BOOL Base64::decodeMemMap(LPCTSTR fIn, LPCTSTR fOut)
{
 HANDLE hIn, hOut, hInMap, hOutMap;
 LPSTR pIn, pInFile;
 LPSTR pOut, pOutFile;
 DWORD dwInLow, dwOutLow;
 DWORD dwOutLen = 0;
 TCHAR szBuf[3] = "";

 hIn = CreateFile(fIn, GENERIC_READ, 0, NULL,
  OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
 dwInLow = GetFileSize(hIn, NULL);
 if (dwInLow >= 2)
 {
  SetFilePointer(hIn, -2, NULL, FILE_END);
  DWORD result;
  ReadFile(hIn, szBuf, 2, &result, NULL);
  dwOutLow = CalcBase64toANSILen(dwInLow, szBuf);
 }
 hInMap = CreateFileMapping(hIn, NULL, PAGE_READONLY,
  0, 0, NULL);
 pInFile = (LPSTR)MapViewOfFile(hInMap, FILE_MAP_READ, 0, 0, 0);
 
 hOut = CreateFile(fOut, GENERIC_READ|GENERIC_WRITE, 0, NULL,
  CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
 hOutMap = CreateFileMapping(hOut, NULL, PAGE_READWRITE,
  0, dwOutLow, NULL);
 pOutFile = (LPSTR)MapViewOfFile(hOutMap, FILE_MAP_WRITE, 0, 0, dwOutLow);

 //转换
 pIn = pInFile;
 pOut = pOutFile;
 decode(pIn, dwInLow, pOut, &dwOutLen);

 UnmapViewOfFile(pOutFile); UnmapViewOfFile(pInFile);
 CloseHandle(hOutMap); CloseHandle(hInMap);
 CloseHandle(hOut); CloseHandle(hIn);
 return TRUE;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    BOOL encode()
// 功能:    将ANSI格式文件转成Base64格式文件
// 参数:    cstrSrc ANSI格式的文件名
//   cstrDes Base64格式的文件名
// 返回值:  BOOL TRUE(成功) FALSE(失败)
// 日期:    [6/24/2005]
//////////////////////////////////////////////////////////////////////////
BOOL Base64::encode(const CString cstrSrc, const CString cstrDes)
{
 try
 {
  CFile file(cstrSrc, CFile::modeRead);
  CFile desFile(cstrDes, CFile::modeWrite | CFile::modeCreate);

  int length = file.GetLength();
  while (length>0)
  {
   int size = 4095; //必须是3的倍数,不然就被'='所烦。解码只要以四的倍数即可
   PSTR buffer=NULL;
   buffer = new TCHAR[size];
   UINT nBytesRead = file.Read(buffer, size);

   // 将Base64格式写入文件
   PSTR pszBase64 = AllocMemBase64(nBytesRead);
   DWORD dwBase64 = 0;
   encode(buffer, nBytesRead, pszBase64, &dwBase64);
   desFile.Write(pszBase64, dwBase64);
   FreeMemBase64(pszBase64);
   delete[] buffer;
  
   length -= nBytesRead;
  }
 }
 catch(CFileException *e)
 {
//   MessageBox(NULL, e->ReportError(), "error", MB_OK);
  e->Delete();
  return FALSE;
 }

 return TRUE;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    BOOL decode()
// 功能:    将Base64格式文件转成ANSI格式文件
// 参数:    cstrSrc Base64格式的文件名
//   cstrDes ANSI格式的文件名
// 返回值:  BOOL TRUE(成功) FALSE(失败)
// 日期:    [6/24/2005]
//////////////////////////////////////////////////////////////////////////
BOOL Base64::decode(const CString cstrSrc, const CString cstrDes)
{
 try
 {
  CFile file(cstrSrc, CFile::modeRead);
  CFile desFile(cstrDes, CFile::modeWrite | CFile::modeCreate);

  // 读取ANSI文件放入cstrANSI
  int length = file.GetLength();
  while (length>0)
  {
   int size = 4096; //必须是4的倍数
   PSTR buffer=NULL;
   buffer = new TCHAR[size];
   UINT nBytesRead = file.Read(buffer, size);

   PSTR pszANSI = AllocMemANSI(nBytesRead);
   DWORD dwANSI = 0;
   decode(buffer, nBytesRead, pszANSI, &dwANSI);
   desFile.Write(pszANSI, dwANSI);
   FreeMemANSI(pszANSI);
   delete[] buffer;

   length -= nBytesRead;
  }
 }
 catch(CFileException *e)
 {
//   MessageBox(NULL, e->ReportError(), "error", MB_OK);
  e->Delete();
  return FALSE;
 }

 return TRUE;
}

-===================

PHP实现Base64编码解码类的详细教程 在自定义Base64编解码类时,我们需要首先定义类的基本结构,包括它的属性和方法。以下是一个简化版的Base64类的结构设计:// 将输入数据编码成Base64字符串// 将Base64字符串解码回原始数据// 内部使用的方法,处理数据分组的编码// 内部使用的方法,处理数据分组的解码// 更多辅助方法可以在这里定义,例如错误处理等。 阅读详情

相关推荐

Base64编码(VC++实现)

Base64内容传送编码(VC++实现):常用于电子邮件的数据传输中

【转】VC Base64编解码

#include #include unsigned char * base64=(unsigned char *)"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // 编码CString Base64Encode(CString src, int srclen){ int n, buflen, i,

奋斗 1397

晶晨S905L3S/S905L3SB芯片刷机实战:BL加载工具与线刷固件全解析

本文针对晶晨S905L3S/S905L3SB芯片电视盒子刷机时常见的2%失败问题,提供了两种核心解决方案。一是使用已集成特殊通信协议的专用版USB Burning Tool(如V2.2.5/V2.2.7),二是采用旧版工具配合独立的BootLoader加载工具。文章详细解析了两种方案的原理、操作步骤、固件选择及常见问题排查,旨在帮助用户成功完成刷机,让老旧设备焕发新生。

weixin_29238147的博客 1113

c++/mfc base64编解码 base64编码 base64解码

unsigned char * base64=(unsigned char *)"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";   CString base64encode(CString src,int srclen) {      int n,buflen,i,j;      static un

pornographer的专栏 4423

Xilinx HydraMini试玩教程

HydraMini是Xilinx推出的基于Pynq-Z2开发板的自动驾驶开发小车,其有着简单易学、高灵活性、高扩展性、高性能等优良特性,是研究人员和学生进入自动驾驶领域的一个平台。本教程会通过最基础的讲解和步骤带领读者熟悉这个平台的基本开发流程。

qq_25762163的博客 1773

【Cadence】 ADS Dynamic Link使用教程

在Cadence617上使用ADS Dynamic Link

乾巽的博客 6081

MFC封装的base64编码解码函数

函数本就是网上下载的,经过我修改并测试通过以后,封装成C++代码了,并且使用了MFC的数据结构,懂C或C++的朋友可以拿过去稍作修改就可以用了。 提醒:作为C函数,在进行base64编码时一定要给够缓冲区,base64是将8比特数据封装到6比特里,所以缓冲区大小应该为原数据长度 x 4 / 3 + 3,同理,解码的时候则是原数据长度 x 3 / 4 +4,为什么+3、+4?这是因为整除会抛弃余数,余数最大值分别为:2、3,+3、4,多了1个字节,正好给结尾的字符0准备。 #include "StdAfx.h

canlynetsky的博客 1364

华为MA5620配置宽带及语音实例

华为EPON配置实例1、公共部分和宽带PPPOE部分用串口用户名密码root/mduadminMA5620E>enableMA5620E#configMA5620E(config)#MA5620E(config)#sysnamebigcow/给设备起名字/****之前为公共部一、建vlan和地址bigcow(config)#vlan100...

weixin_33862041的博客 6348

base64加密解密

因为jsp是写在web-info下的,只能后台访问,只能request跳转,在登陆的时候因为是request跳转,所以想加密url中的参数 ps:操蛋的form表单提交登陆后刷新会导致重复提交。。。。 js // base64加密开始 var keyStr = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstu...

略略略的博客 996

麒麟操作系统安装达梦数据库ARM版

Linux安装达梦数据库ARM版

运维@小兵的博客 8771

华为交换机、路由器配置静态路由实现不同网段通信

华为交换机、路由器配置静态路由实现不同网段通信。在主核心交换机上配置vlanif10 192.168.10.254/24,vlanif20 192.168.20.254/24,vlanif100 192.168.100.1/24,PC1:192.168.10.1能ping通PC2:192.168.20.1,也能ping通PC3:192.168.30.1,交换机和路由器使用静态路由。

星如雨落 6464

java base64 编码 类_java版base64编码解码类

较早的java版本没有直接提供base64编码处理的类,都是通过其他类库的附加功能实现。而对于android平台,又有自己的base64支持类, 导致代码影响跨平台。所以就自己写了个base64编码处理的类,这样就可以同一套代码运行在android平台和se平台了。packagecom.hoverlees.utils;/***@authorhoverleeshttp://www.hoverlees...

weixin_36145673的博客 215

YOLOv8改进策略【Neck】| CGA Fusion:内容引导的注意力融合模块,空间权重引导的多模态特征自适应融合

本文记录的是利用CGA Fusion 模块改进 YOLOv8 的多模态融合部分。(Content-Guided Attention Fusion)通过内容引导注意力生成空间权重,引导高低层特征的自适应融合。本文利用模块,通过内容引导注意力生成空间权重,自适应地融合两个模态的特征,在特征融合阶段实现跨模态语义对齐与噪声抑制,增强对不同模态互补特征的利用能力,从而提升模型在多模态场景下的检测鲁棒性与准确性。DEA-Net: Single image dehazing based on detail-enhanc

Limiiiing的博客 285

base64编码和解码类

/**  * base64编码和解码类  * Base64.java  * @author vincent chen  * @since 2012 Jun 25, 2012 8:09:05 PM  */ public class Base64Coder {     // The line separator string of the operating system.     p

chong7171的专栏 616

【Python爬虫教程】第3篇-解决使用reqeusts遇到的ProxyError异常

Python request代理错误提示“HTTPSConnectionPool, Cannot connect to proxy, no such file or directory”

分享技术,记录思考和感悟 1509

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

java base64 编码 类_java base64编码和解码的三种方式 | 学步园

方式一:使用commons-codec.jar/*** @param bytes* @return*/public static byte[] decode(final byte[] bytes) {return Base64.decodeBase64(bytes);}/*** 二进制数据编码为BASE64字符串** @param bytes* @return* @throws Exception...

weixin_30131185的博客 349

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

c# Base64编码解码类

c# Base64编码解码类

Debug-123 431

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

基于flash AS3.0 的BASE64编码与解码类

代码 Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--&gt;//调用代码: import com.dynamicflash.utils.Base64; //编码和解码字符串 var source:Stri...

优秀技术文章收录 383

AS3的BASE64编码与解码类

最近任务紧,工作忙,好久没来更新我的BLOG了。今天在国外网站上淘到一个很好用的AS3的BASE64类感觉写得简洁而强大。很好,赶快放上来。调用代码:import com.dynamicflash.utils.Base64;      //编码和解码字符串      var source:Str

blacksource的专栏 4831

Base64 Encode/Decode Class C++ SourceCode - Base64编码/解码 类 C++ 源码

Base64 Encode/Decode Class C++ SourceCode - Base64编码/解码 类 C++ 源码  1、Base64.h // Base64.h: interface for the CBase64 class.////////////////////////////////////////////////////////////////////

纪飞的博客 8969

基于 flash AS3.0 的BASE64编码与解码类

版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明 http://programmer.blogbus.com/logs/36436446.html 在国外网站上淘到一个很好用的AS3的BASE64类感觉写得简洁而强大。很好,赶快放上来。 调用代码: 01 import com.dynamicflash.utils.Base64;      02 //编码和

Manketon的专栏 2449

php的Url 安全的base64编码解码类

用于 http传输的,安全的url base64编码,主要对 +,-,=字符进行了处理,以防止注入的产生

hzbigdog的专栏 1235

Java 版本的 Base64 编码解码类

J2SE 中没有标准的 Base64 编码解码类,虽然可以使用非标准的 sun.misc.BASE64Encoder 和 sun.misc.BASE64Decoder,但是用非标准的东西总感觉不好。所以自己写了一个 Base64 编码解码的类。这个类只有 2 个方法,一个 encode,一个 decode,encode 用来将 byte 数组转化为 Base64 字符串,而 decode 则将 B

走向资深架构师的旅程 1069

java常用工具类:实现base64加盐编码、解码

本文实现加盐的base64编码和解码

m0_71817461的博客 514

java base64 编码 类_java base64编码解码工具类

自己编写的java base64编码解码工具类使用起来很方便就分享出来了,以下的案例使用的base64 utf-8编码,如果想改gbk编码只需要传不同的值即可,下面来解析一下base64的使用。packagecom.baidu;importjava.io.UnsupportedEncodingException;importjava.nio.charset.Charset;importco...

weixin_39707725的博客 410
上一篇: POP3Dlg.cpp
下一篇: 简单实现强大的加密功能——CryptoAPI
iiprogram
博客等级 码龄25年 1068粉丝 1515原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值