base64编码--c程序

const unsigned char TAB[] = "ABCDEFGHIJKLNMOPQRSTUVWXYZabcdefghijklnmopqrstuvwxyz123456789+/";
/*
函数功能:base64编码
形参:
input输入的数据流
inlen输入的数据流长度
output输出的字符串
返回值:编码以后的有效字符串长度
*/
int base64_encode( unsigned char *input, int inlen,unsigned char *output)
{
    int i = 0, j = 0;
    unsigned char com_byte = inlen % 3;

    switch(com_byte)
    {
        case 0:com_byte = 0;
        break;
        case 1:com_byte = 2;
        break;
        case 2:com_byte = 1;
        break;
        default:break;
    }
    inlen += com_byte;
    for(i = 0,j = 0;i < inlen;i+=3,j+=4)
    {
        output[j] = TAB[input[i] >> 2];
        output[j+1] = TAB[(input[i]&0x3)<<4 | (input[i+1] >> 4)];
        output[j+2] = TAB[(input[i+1]&0xf) << 2 | (input[i+2] >> 6)];
        output[j+3] = TAB[input[i+2]&0x3f];
    }
    if(com_byte == 1)
        output[j - 1] = '=';
    else if(com_byte == 2)
    {
        output[j - 1] = '=';
        output[j - 2] = '=';
    }
    output[j] = 0;
    return j;
}
/*
函数功能:base64解码
形参:
input输入的字符串
inlen输入的字符串长度
output输出的数据流
返回值:解码以后的有效数据流长度
*/
int base64_decode( unsigned char *input, int inlen,unsigned char *output)
{
    int i = 0, j = 0;
    unsigned char temp[100];

    for(i = 0;i < inlen;i++)
    {
        for(j = 0;j < strlen(TAB);j++)
        {
            if(TAB[j] == input[i])
            {
                temp[i] = j;
                break;
            }
        }
    }
    for(i = 0,j = 0;i < inlen;i+=4,j+=3)
    {
        output[j] = temp[i] << 2 | ((temp[i+1] >> 4) & 0x3);
        output[j+1] = ((temp[i+1]&0xf) << 4) | ((temp[i+2] >> 2) & 0xf);
        output[j+2] = ((temp[i+2]&0x3) << 6) | (temp[i+3]& 0x3f);
    }
    if(input[inlen - 1] == '=')
    {
        if(input[inlen - 2] != '=')
        {
            output[j - 1] = 0;
            j -= 1;
        }

        else
        {
            output[j - 1] = 0;
            output[j - 2] = 0;
            j -= 2;
        }

    }
    else
        output[j] = 0;
    return j;
}

int main(void)
{
    unsigned char a[] = {1,2,3,4,5,6,7};
    unsigned char b[] = "AQIDBAUGBw==";
    int i = 0;
    int outlen = 0;
    unsigned char encodebuf[100];
    unsigned char decodebuf[100];

    outlen = base64_encode(a, sizeof(a), encodebuf);
    printf("编码后字符串为 = %s\n", encodebuf);
    printf("编码后的字符串长度为 = %d\n", outlen);

    outlen = base64_decode(b, sizeof(b) - 1, decodebuf);//-1是因为sizeof还包含了结束符,实际结束符是不参与运算的
    printf("解码后的buf数据长度为 =  %d\n", outlen);
    printf("解码后的buf数据为 =  \n");
    for(i = 0; i < outlen; i++)
        printf("%d ", decodebuf[i]);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值