C中的Base64编码填充

时间:2016-03-10 01:12:14

标签: c

我正在写一个base64编码器和解码器,并且它几乎具有完整的功能,我只需要能够用等号填充编码数据,如果输入字节数没有四舍五入到3的倍数。我是相对来说是C的新手,我不确定如何检测字节数或相应地填充输出。这就是我到目前为止所拥有的

void encode(char* src, char* dest) {

    char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    unsigned char first = (src[0] >> 2);

    unsigned char second = (src[0] << 4) | (src[1] >> 4);
    second = (second << 2);
    second = (second >> 2);

    unsigned char third = (src[1] << 2) | (src[2] >> 6);
    third = (third << 2);
    third = (third >> 2);

    unsigned char fourth = (src[2]);
    fourth = (fourth << 2);
    fourth = (fourth >> 2);

    dest[0] = base64[first];
    dest[1] = base64[second];
    dest[2] = base64[third];
    dest[3] = base64[fourth];

}

我的解码器方法......

void decode(char* src, char* dest) {

    char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    int i;
    int j;
    int index;

    for(i = 0; i < 4; i++) {
        index = 0;
        for(j = 0; j < 64; j++) {
            if (src[i] == base64[j]) {
                src[i] = index;
            } else {
                index++;
            }
        }
    }

    char first = (src[0] << 2) | (src[1] >> 4);
    char second = (src[1] << 4) | (src[2] >> 2);
    char third = (src[2] << 6) | (src[3]);

    dest[0] = first;
    dest[1] = second;
    dest[2] = third;
}

如果这还不够,我还需要提供剩余的代码,我可以这样做。

0 个答案:

没有答案