c_cpp Base64编码和解码
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp Base64编码和解码相关的知识,希望对你有一定的参考价值。
#include <stdlib.h>
#include <string.h>
/*
** modified by wention 11.22.2013
**
** more information about original please visite http://base64.sourceforge.net/
**
*/
/*
** Translation Table as described in RFC1113
*/
static const char cb64[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/*
** Translation Table to decode (created by author)
*/
static const char cd64[]="|$$$}rstuvwxyz{$$$$$$$>?@ABCDEFGHIJKLMNOPQRSTUVW$$$$$$XYZ[\\]^_`abcdefghijklmnopq";
/*
** encodeblock
**
** encode 3 8-bit binary bytes as 4 '6-bit' characters
*/
static void encodeblock( unsigned char *in, unsigned char *out, int len )
{
out[0] = (unsigned char) cb64[ (int)(in[0] >> 2) ];
out[1] = (unsigned char) cb64[ (int)(((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4)) ];
out[2] = (unsigned char) (len > 1 ? cb64[ (int)(((in[1] & 0x0f) << 2) | ((in[2] & 0xc0) >> 6)) ] : '=');
out[3] = (unsigned char) (len > 2 ? cb64[ (int)(in[2] & 0x3f) ] : '=');
}
/*
** encode
**
** base64 encode a stream adding padding and line breaks as per spec.
*/
int base64_encode( unsigned char *infile,unsigned long insize, unsigned char *outfile, int linesize )
{
unsigned char in[3]={0};
unsigned char out[4]={0};
int i,len, cin = 0,cout = 0,blocksout = 0;
*in = (unsigned char) 0;
*out = (unsigned char) 0;
while( cin < insize ) {
len = 0;
for( i = 0; i < 3; i++ ) {
in[i] = (unsigned char) infile[cin++];
if( cin <= insize ) {
len++;
}
else {
in[i] = (unsigned char) 0;
}
}
if( len > 0 ) {
encodeblock( in, out, len );
memmove(&outfile[cout],out,4);
cout+=4;
blocksout++;
}
if( blocksout >= (linesize/4) || cin >= insize ) {
if( blocksout > 0 ) {
memmove( &outfile[cout], "\r\n", 2 );
cout+=2;
}
blocksout = 0;
}
}
return true;
}
/*
** decodeblock
**
** decode 4 '6-bit' characters into 3 8-bit binary bytes
*/
static void decodeblock( unsigned char *in, unsigned char *out )
{
out[ 0 ] = (unsigned char ) (in[0] << 2 | in[1] >> 4);
out[ 1 ] = (unsigned char ) (in[1] << 4 | in[2] >> 2);
out[ 2 ] = (unsigned char ) (((in[2] << 6) & 0xc0) | in[3]);
}
/*
** decode
**
** decode a base64 encoded stream discarding padding, line breaks and noise
*/
int base64_decode( unsigned char *infile,unsigned long insize, unsigned char *outfile )
{
unsigned char in[4]={0};
unsigned char out[3]={0};
int v;
int i, len, cin =0, cout =0;
while( cin < insize ) {
for( len = 0, i = 0; i < 4 && cin < insize; i++ ) {
v = 0;
while( cin < insize && v == 0 ) {
v = infile[cin++];
if( v != 0 ) {
v = ((v < 43 || v > 122) ? 0 : (int) cd64[ v - 43 ]);
if( v != 0 ) {
v = ((v == (int)'$') ? 0 : v - 61);
}
}
}
if( cin < insize ) {
len++;
if( v != 0 ) {
in[ i ] = (unsigned char) (v - 1);
}
}
else {
in[i] = (unsigned char) 0;
}
}
if( len > 0 ) {
decodeblock( in, out );
memmove(&outfile[cout],out,3);
cout+=3;
}
}
return true;
}
以上是关于c_cpp Base64编码和解码的主要内容,如果未能解决你的问题,请参考以下文章
c_cpp 将base 64映像解码为cvmat opencv 3.0