在C语言中,实现Base64编码和解码可以通过以下步骤进行:
以下是一个简单的示例:
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
// Base64字符映射表
const char *base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// Base64编码函数
char *base64_encode(const unsigned char *input, int length) {
int i, j;
int encoded_length = 4 * ((length + 2) / 3);
char *encoded = (char *)malloc(encoded_length + 1);
if (encoded == NULL) return NULL;
for (i = 0, j = 0; i< length;) {
int octet_a = i< length ? input[i++] : 0;
int octet_b = i< length ? input[i++] : 0;
int octet_c = i< length ? input[i++] : 0;
int triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
encoded[j++] = base64_chars[(triple >> 18) & 0x3F];
encoded[j++] = base64_chars[(triple >> 12) & 0x3F];
encoded[j++] = base64_chars[(triple >> 6) & 0x3F];
encoded[j++] = base64_chars[(triple >> 0) & 0x3F];
}
for (i = 0; i < (3 - (length % 3)) % 3; i++) {
encoded[encoded_length - 1 - i] = '=';
}
encoded[encoded_length] = '\0';
return encoded;
}
// Base64解码函数
unsigned char *base64_decode(const char *input, int *output_length) {
int i, j;
int decoded_length = strlen(input) * 3 / 4;
unsigned char *decoded = (unsigned char *)malloc(decoded_length + 1);
if (decoded == NULL) return NULL;
for (i = 0, j = 0; i < strlen(input);) {
int sextet_a = i < strlen(input) ? strchr(base64_chars, input[i++]) - base64_chars : 0;
int sextet_b = i < strlen(input) ? strchr(base64_chars, input[i++]) - base64_chars : 0;
int sextet_c = i < strlen(input) ? strchr(base64_chars, input[i++]) - base64_chars : 0;
int sextet_d = i < strlen(input) ? strchr(base64_chars, input[i++]) - base64_chars : 0;
int triple = (sextet_a << 18) + (sextet_b << 12) + (sextet_c << 6) + sextet_d;
if (j < decoded_length) decoded[j++] = (triple >> 16) & 0xFF;
if (j < decoded_length) decoded[j++] = (triple >> 8) & 0xFF;
if (j < decoded_length) decoded[j++] = (triple >> 0) & 0xFF;
}
while (decoded[--j] == '=') {
decoded_length--;
}
decoded[decoded_length] = '\0';
*output_length = decoded_length;
return decoded;
}
int main() {
const char *input = "Hello, World!";
int length = strlen(input);
// Base64编码
char *encoded = base64_encode((unsigned char *)input, length);
printf("Base64编码: %s\n", encoded);
// Base64解码
int output_length;
unsigned char *decoded = base64_decode(encoded, &output_length);
printf("Base64解码: %.*s\n", output_length, decoded);
free(encoded);
free(decoded);
return 0;
}
这个示例中,我们首先定义了一个Base64字符映射表,然后实现了Base64编码和解码函数。在main
函数中,我们对一个字符串进行编码和解码操作,并输出结果。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。