Base64 encoding decoding implementation (C language)

zhaozj2021-02-16  39

/ ************************************************** ************** This is a sample routine of base64 Algorithm.The Goal Is To Illustrate Principles, SO Some Details May Be ignored. Author Email: zhangwu2003@163.com **** *********************************************************** *********** / # include #include #include

Char * ch64 = "Abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789 /";

Unsigned char * encode (unsigned char * src, int srclen) {Int n, buflen, i, j; int paing = 0; unsigned char * buf; static unsigned char * dst;

BUF = src; buflen = n = srcle; if (n% 3! = 0) / * Pad with '=' by using a temp buffer * / {pading = 1; buflen = n 3-n% 3; buf = Malloc (BUF, 0, BUFLLEN 1); Memcpy (BUF, SRC, N); for (i = 0; i <3-n% 3; i ) BUF [N I] = '=';} DST = malloc (buflen * 4/3 1); MEMSET (DST, 0, BUFLLEN * 4/3 1); for (i = 0, j = 0; i > 2; DST [J 1] = ((BUF [I] & 0x03) << 4) ((BUF [i 1] & 0xF0) >> 4); DST [J 2] = ((BUF [i 1] & 0x0f) << 2) ((BUF [i 2] & 0xc0) >> 6); DST [J 3] = BUF [i 2] & 0x3f;} for (i = 0; i

Unsigned char * decode (unsigned char * src) {INT N, I, J; unsigned char * p; static unsigned char * dst;

n = strlen (src); for (i = 0; i > 4); DST [J 1] = ( (SRC [I 1] & 0x0F) << 4) ((SRC [i 2] & 0x3c) >> 2); DST [J 2] = ((SRC [i 2] & 0x03) << 6) SRC [i 3];} Return Dst;} void main () {// char * src = "zhangwu Zhang Wu"; char src [] = {'1', '2', '3', 0, 'a', 'b', '*', 0, 'a', 'b', '$'; unsigned char * dst1; unsigned char * DST2; unsigned int i;

DST1 = Encode (SRC, 11); / * The second parameter must acid with the first one * / printf ("% s / n", dst1); DST2 = decode (DST1); for (i = 0; i <_msize (DST2); I ) Printf ("% C", DST2 [I]);

Free (DST1); Free (dst2);}

转载请注明原文地址:https://www.9cbs.com/read-26171.html

New Post(0)