使用C语言实现Base64编码与解码
Base64是一种基于64个可打印字符来表示二进制数据的编码方法。它通常用于在HTTP协议、电子邮件和其他场合下,将小型数据(如文本)编码为只包含可打印字符的形式,以便于传输。
在C语言中,我们可以通过以下的代码来实现Base64编码和解码的功能:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char b64chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int b64encode(const void* data, int size, char** str) {
const unsigned char* bytes = (const unsigned char*)data;
int out_size = 4 * ((size + 2) / 3);
char* res = (char*)malloc(out_size + 1);
if (res == NULL) return -1;
int i, j;
for (i = 0, j = 0; i < size; ) {
uint32_t x = 0;
int n;
for (n = 0;