Linux之gmime的编码和解码应用--不用自己造轮子

1、gmime资源

下载地址:http://download.chinaunix.net/download/0004000/3867.shtml

下载:gmime-2.6.7.tar.xz

2、编码和解码主要文件

# xz -d gmime-2.6.7.tar.xz         //解压.xz文件

# tar xf gime-2.6.7.tar

主要文件:

gmime-encodings.c

gmime-encodings.h

gmime-table-private.h      //被调用

找到这几个文件才是关键,里面的实现方法,了解了相关编码和解码的原理就容易明白;

3、示例

直接看简单的应用代码:

int main(void){

printf("-------encode----------\n");


GMimeEncoding myencode;              //编码结构体
GMimeContentEncoding encode_type;    //编码类型
unsigned char *encode_outbuf = NULL; //指向编码后内存空间
size_t elen = 0;                     

const unsigned char *encode_inbuf = "This is a test.";                    //aGVsbG8gd29ybGQh
encode_type = g_mime_content_encoding_from_string ("base64");          //base64编码为例子
g_mime_encoding_init_encode (&myencode, encode_type);                  //初始化编码结构体
elen = g_mime_encoding_outlen (&myencode, sizeof(encode_inbuf));       //计算编码后所需要的内存空间大小
encode_outbuf = calloc(1,elen + 1);                                    //分配存储编码字符的内存空间,多一个填充'\0'
if(NULL == encode_outbuf){
printf("encode_outbuf:calloc failed.\n");
return -1;
}
elen = g_mime_encoding_flush (&myencode, encode_inbuf, strlen(encode_inbuf),encode_outbuf);   
//编码,没有后续编码内容调用flush,//若有后续编码内容可以先调用step,最后再调用flush
printf("elen = %d,encode_outbuf = %s\n",elen,encode_outbuf);
free(encode_outbuf);
encode_outbuf = NULL;

printf("--------decode---------\n");
GMimeEncoding mydecode;     //解码结构体
GMimeContentEncoding decode_type;   //解码类型
unsigned char *decode_outbuf = NULL;//指向解码后内存空间
size_t dlen = 0;

const unsigned char *decode_inbuf = "VG9kYXkgaXMgYSBnb29kIGRheS4=";    //Today is a good day.
decode_type = g_mime_content_encoding_from_string ("base64");          //base64解码为例子
g_mime_encoding_init_decode(&mydecode, decode_type);  //初始化编码结构体
dlen = g_mime_encoding_outlen (&mydecode, sizeof(decode_inbuf));//计算解码后所需要的内存空间大小
decode_outbuf = calloc(1,dlen + 1);//分配存储解码字符的内存空间,多一个填充'\0'
if(NULL == decode_outbuf){
printf("decode_outbuf:calloc failed.\n");
return -1;
}
dlen = g_mime_encoding_flush (&mydecode, decode_inbuf, strlen(decode_inbuf),decode_outbuf);
printf("dlen = %d,decode_outbuf = %s\n",dlen,decode_outbuf);
free(decode_outbuf);
decode_outbuf = NULL;
return 0;
}

编译:gcc gmime-encoding.c -I/usr/include/glib-2.0 -lglib-2.0

运行结果:

-------encode----------
elen = 21,encode_outbuf = VGhpcyBpcyBhIHRlc3Qu

--------decode---------
dlen = 20,decode_outbuf = Today is a good day.


补:

关于base64解码过程,可以先将4个base64字符填充到4字节的变量中,然后结合char*和移位来实现3个8bits

的提取,这样就能保证正常解码编码内容,多余的base64字符可以直接丢弃或暂存储。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值