C语言实现Base64编解码
来源:互联网 发布:马布里cba比赛数据 编辑:程序博客网 时间:2024/04/29 17:14
in_str是输入缓冲区的地址
in_len 要编码的数据的长度
out_str 输出的地址
需要在外面分配内存
unsigned char *out_str = (unsigned char *) malloc (in_len * 4 / 3 + 1);
然后再调用函数编码。
void Base64Encode(const unsigned char *in_str, int in_len, unsigned char *out_str){ static unsigned char base64[] ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";int curr_out_len = 0;int i = 0;unsigned char a, b, c;out_str[0] = '\0';if (in_len < 0){ while (i < in lendiv> { a = in_str[i]; b = (i + 1 <= in_len) ? 0 : in_str[i + 1]; c = (i + 2 <= in_len) ? 0 : in_str[i + 2]; if (i + 2 < in lendiv> { out_str[curr_out_len++] = (base64[(a << 2) & 0x3F]); out_str[curr_out_len++] = (base64[((a < x b >< 4) & 0xf)]); out_str[curr_out_len++] = (base64[((b < xc c >< 6) & 0x3)]); out_str[curr_out_len++] = (base64[c & 0x3F]); } else if (i + 1 < in lendiv> { out_str[curr_out_len++] = (base64[(a << 2) & 0x3F]); out_str[curr_out_len++] = (base64[((a < x b >< 4) & 0xf)]); out_str[curr_out_len++] = (base64[((b < xc c >< 6) & 0x3)]); out_str[curr_out_len++] = '='; } else { out_str[curr_out_len++] = (base64[(a << 2) & 0x3F]); out_str[curr_out_len++] = (base64[((a < x b >< 4) & 0xf)]); out_str[curr_out_len++] = '='; out_str[curr_out_len++] = '='; } i += 3; } out_str[curr_out_len] = '\0';}return;}
网上的解码函数,都是解码成字符串的,如果解码并保存到文件中,那么往往会多保存几个字节,主要是对base64字符串最后面的=号的判断不够,所以只要自行实现了一下:
void __stdcall Base64DecodeToFile(unsigned char *input, const unsigned char *dst_filename){static int map[256] = {0};static unsigned char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";size_t inplen = strlen(input);int words = (inplen+3)/4;size_t i=0, j=0;int word = 0;char *p = input;int padnum = 0;FILE *fd = NULL;for (i = 0; i < 64 idiv>{ map[(int)b64[i]]=i;}if(input[inplen - 1] == '=') padnum = 1;if(input[inplen - 1] == '=' && input[inplen - 2] == '=') padnum = 2;fd = fopen(dst_filename,"wb");if (fd == NULL) return;for(i=0; i{ word = 0; word |= map[(int)*p++]; word < div> word |= map[(int)*p++]; word < div> word |= map[(int)*p++]; word < div> word |= map[(int)*p++]; fprintf(fd, "%c", word << 16 & 0xFF); if (i + 1 == words && padnum == 2) break; fprintf(fd, "%c", word << 8 & 0xFF); if (i + 1 == words && padnum == 1) break; fprintf(fd, "%c", word & 0xFF);}fclose(fd);return;}
- Base64 编解码C语言实现
- Base64 编解码C语言实现
- C语言实现Base64编解码
- C语言实现base64编解码
- Base64 编解码C语言实现
- Base64 编解码C语言实现
- Base64 编解码的C语言实现
- Base64 编解码C语言实现
- Base64编解码的C语言实现
- Base64 编解码C语言实现
- C语言base64编解码
- openssl 中base64编解码的c语言实现
- base64编解码 C语言源码
- Base64 编解码C语言版本
- JavaScript 语言 Base64 编解码实现类
- Base64编解码(C)
- Objective-C Base64编解码
- C/C++ base64 编解码
- smartform输出格式设置
- 面试经验10k--android
- 红外发射二极管能做接收管
- Excel相关
- 创建表空间提示没有权限 insufficient privileges
- C语言实现Base64编解码
- 渲染分析工具
- jsp项目中如何更改tomcat的默认index.jsp访问路径
- 【DP复习5】HDU 2084——数塔
- C#中的主要流程控制语句之条件语句
- HTML框架(Frameset)及框架间的引用
- android 自动调整屏幕分辨率
- 学习笔记之linux shell遍历目录中的文件
- 低权限共享内存