base64 很常见。其原理是 将每个ascii 字符视为 unsigned char, 每三个char 3*8位,拆分为 4*6位char来存储。其中高两位用0填充。
今天看了下,自己实现。环境: VC6
上自己的代码:
#include <iostream>
#include <string>
using namespace std;
static const std::string data_str="ABCDEFGHIJKLMBOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
void encode_char(char src[], char* dest)
{
dest[0] = ( src[0] >> 2 ) & 0x3f;
short t = ( src[1] >> 4 );
dest[1] = t & 0x0f;
t = ( src[0] & 0x3 );
t = t << 4;
dest[1] = dest[1] + t;
t = ( src[1] & 0xf );
dest[2] = t<<2;
t = src[2] >> 6;
dest[2] += t & 0x03;
dest[3] = ( src[2] & 0x3f ) ;
return ;
}
std::string encode_str(std::string src_str)
{
size_t len = src_str.size();
int i = 0;
char src[3];
char dest[4] = {0};
std::string dest_src;
for( int j = 0; j < len; ++j ) {
src[i++] = src_str[j];
if( 3 == i ) {
encode_char( src, dest );
for( i = 0; i < 4; i++) {
dest_src += data_str[dest[i]];
dest[i] = 0;
}
i = 0;
}
}
if( 0 != i ) {
for( j = i; j < 3; ++j ) {
src[j] = '\0';
}
encode_char( src, dest );
for( i=0; i < 4; ++i ) {
dest_src += data_str[ dest[i] ];
}
}
return dest_src;
}
void decode_char(char src[], char *dest)
{
short t = ( src[0] << 2 ) ;
dest[0] = t & 0xfc;
t = ( src[1] >> 4 );
dest[0] += t & 0x3;
t = ( src[1] << 4 );
dest[1] = t & 0xf0;
t = ( src[2] >> 2 );
dest[1] += t & 0xf;
t = ( src[2] << 6 );
dest[2] = t & 0xc0;
dest[2] += src[3];
}
std::string decode_str(std::string dest_str)
{
size_t len = dest_str.size();
int i = 0;
char src[4];
char dest[3];
std::string ret;
for( int j = 0; j < len; ++j ) {
src[i++] = data_str.find( dest_str[j] );
if( 4 == i ) {
decode_char( src, dest );
for( i = 0; i < 3; ++i ) {
ret += dest[i];
dest[i] = 0;
}
i = 0;
}
}
return ret;
}
int main()
{
// std::string _str( "hello wang fang" );
std::string _str;
cout<<"please Enter a String:";
cin>>_str; // 有 bug, cin 将 space tab 和enter 作为输入结束符,如果输入 hello world 只会接收hello,详细请参考 下面给出链接
std::string str( encode_str( _str ) );
cout<<str.c_str()<<endl;
cout<< decode_str( str ).c_str()<<endl;
return 0;
}
有关cin的使用,输入输出: 点击这里 。