わびさびサンプルソース

WindowsやHTML5などのプログラムのサンプルコードやフリーソフトを提供します。

BASE64エンコード

std::stringをBASE64でエンコードします。

#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <string>



/*
	BASE64エンコード
*/
std::string Base64Encode
(
	std::string strData
)
{
	const static char* baBase64tbl = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

	std::string::iterator ite    = strData.begin();
	std::string::iterator iteEnd = strData.end();


	/*
		変換用バッファ
	*/
	union {
		unsigned char baBuf[ 4 ];
		unsigned long dwValue;
	} uniValue;

	std::string strRet;

	/*
		全データ巡回
	*/
	while( ite != iteEnd ) {

		// バッファ初期化
		uniValue.dwValue = 0;

		// 読みだしたバイト数
		int nByteCount = 1;

		// 1バイト目の取得
		uniValue.baBuf[ 2 ] = (unsigned char)*ite++;

		// 2バイト目の取得
		if ( ite != iteEnd ) {
			uniValue.baBuf[ 1 ] = (unsigned char)*ite++;
			nByteCount++;
		}

		// 3バイト目の取得
		if ( ite != iteEnd ) {
			uniValue.baBuf[ 0 ] = (unsigned char)*ite++;
			nByteCount++;
		}

		switch( nByteCount ) {
		case 3:
			strRet += baBase64tbl[ 0x3f & ( uniValue.dwValue >> 18 ) ];
			strRet += baBase64tbl[ 0x3f & ( uniValue.dwValue >> 12 ) ];
			strRet += baBase64tbl[ 0x3f & ( uniValue.dwValue >>  6 ) ];
			strRet += baBase64tbl[ 0x3f & ( uniValue.dwValue >>  0 ) ];
			break;

		case 2:
			strRet += baBase64tbl[ 0x3f & ( uniValue.dwValue >> 18 ) ];
			strRet += baBase64tbl[ 0x3f & ( uniValue.dwValue >> 12 ) ];
			strRet += baBase64tbl[ 0x3f & ( uniValue.dwValue >>  6 ) ];
			strRet += "=";
			ite = iteEnd;
			break;

		case 1:
			strRet += baBase64tbl[ 0x3f & ( uniValue.dwValue >> 18 ) ];
			strRet += baBase64tbl[ 0x3f & ( uniValue.dwValue >> 12 ) ];
			strRet += "==";
			ite = iteEnd;
			break;
		}
	}

	// BASE64エンコード結果を返す
	return( strRet );
}



/*
	BASE64エンコード
*/
int _tmain
(
	  int argc
	, _TCHAR* argv[]
)
{
	/*
		std::wcoutのロケールを設定
		 これを設定するだけで、std::wcoutで日本語が表示される
		 ようになります。
	*/
	std::wcout.imbue( std::locale( "", std::locale::ctype ) );

	// 変換対象の文字列
	std::string strText = "BASE64でエンコードします。";

	// BASE64エンコードを行います。
	std::string strResult = Base64Encode( strText );

	// 変換結果を表示
	std::cout << strResult.c_str() << std::endl;

	// 正常終了
	return( 0 );
}

実行結果

QkFTRTY0gsWDR4OTg1KBW4NogrWC3IK3gUI=






わびさびサンプルソース

WindowsやHTML5などのプログラムのサンプルコードやフリーソフトを提供します。