unsignedchar*base64_encode(unsignedchar*str){// 1. define the base64 table
unsignedchartable[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";// 2. calculate the length of string after base64 encoding
intstr_len=strlen(str);intlen;if(str_len%3==0){len=str_len/3*4;}else{len=(str_len/3+1)*4;}// 3. Encoding as a group of three 8-bit characters
unsignedchar*res=malloc(sizeof(unsignedchar)*len+1);res[len]='\0';inti,j;for(i=0,j=0;j<str_len;j+=3,i+=4){res[i]=table[str[j]>>2];res[i+1]=table[(str[j]&0b11)<<4|str[j+1]>>4];res[i+2]=table[(str[j+1]&0b1111)<<2|str[j+2]>>6];res[i+3]=table[str[j+2]&0b111111];}// 4. add '=' if needed
switch(str_len%3){case1:res[len-1]='=';res[len-2]='=';break;case2:res[len-1]='=';break;}returnres;}