|
|
楼主 |
发表于 2013-5-27 08:58:10
|
显示全部楼层
/**************************************************************
* Copyright (C) 2006-2013 All rights reserved.
* @Version: 1.0
* @Created: 2013-05-19 10:40
* @Author: chin - qin@126.com
* @Description: 编码规则:
1、把三上字符转换成4个字符
例:字符串“张”
11010101 HEX 5 11000101 HEX:C5
00110101 00011100 00010100
十进制53 十进制34 十进制20 pad
字符’1’ 字符’i’ 字符’U’ 字符’=
不足的字符以'='补齐
2、每76个字符后加一个换行符
*
* @History:
**************************************************************/
#include <stdio.h>
#include <string.h>
#include <malloc.h>
static char base64_code_ch[64] =
{
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O',' ',
'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','+','/'
};
/**
* @brief base64_to_string
*
* @Param: input
* @Param: input_len
* @Param: output_len
*
* Returns: 成功则返回解码后的字符串和长度,失败返回NULL
*/
unsigned char *base64_to_string(const unsigned char *input, size_t input_len, size_t *output_len)
{
unsigned char *output = NULL, buf[4];
int pos = 0;
size_t count = 0, len = 0;
if(input)
{
output = (unsigned char *)malloc(3*(input_len/4) + 1);
if(output)
{
while( *input != '\0' )
{
if( *input != '\n' )
{
for(pos=0; pos < 64; pos++)
{
if( *input == base64_code_ch[pos])
{
buf[count++] = pos;
break;
}
}
if(count == 4)
{
output[len++] = buf[0] << 2 | buf[1] >> 4;
output[len++] = buf[1] << 4 | buf[2] >> 2;
output[len++] = buf[2] << 6 | buf[3];
count = 0;
}
input++;
}
else
{
input++;
}
}
/*处理后四位,两种情况,有一个=号和有两个=号*/
if(count == 2) //两个等于号的情况
{
output[len++] = buf[0] << 2 | buf[1] >> 4;
}
else if(count == 3)
{
output[len++] = buf[0] << 2 | buf[1] >> 4;
output[len++] = buf[1] << 4 | buf[2] >> 2;
}
output[len] = '\0';
if( output_len )
*output_len = len;
return output;
}
}
return NULL;
}
int main(int argc,char *argv[])
{
size_t encode_len;
size_t decode_len;
unsigned char *p2;
if(argc != 2)
{
fprintf(stderr,"Error input !\n");
return 0;
}
encode_len = strlen(argv[1]);
printf("encode_len= %u\n",encode_len);
p2 = base64_to_string( (unsigned char *)argv[1], encode_len, &decode_len );
//p2 = base64_to_string( NULL, encode_len, &decode_len );
if(p2)
printf("decode_len = %u,decode = %s\n",decode_len,p2);
else
printf("NULL\n");
free(p2);
p2 = NULL;
return 0;
}
|
|