下面是一个使用 C 语言实现 Base64 编码和解码的示例。Base64 是一种将二进制数据转换为 ASCII 字符串的编码方式。
Base64 编码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const char base64_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
void base64_encode(const unsigned char *input, size_t length, char *output) {
int i, j;
for (i = 0, j = 0; i < length;) {
uint32_t octet_a = i < length ? input[i++] : 0;
uint32_t octet_b = i < length ? input[i++] : 0;
uint32_t octet_c = i < length ? input[i++] : 0;
uint32_t triple = (octet_a << 16) + (octet_b << 8) + octet_c;
output[j++] = base64_table[(triple >> 18) & 0x3F];
output[j++] = base64_table[(triple >> 12) & 0x3F];
output[j++] = (i > length + 1) ? '=' : base64_table[(triple >> 6) & 0x3F];
output[j++] = (i > length) ? '=' : base64_table[triple & 0x3F];
}
output[j] = '\0';
}
int main() {
const char *data = "Hello, World!";
size_t input_length = strlen(data);
// Base64 encoded string will be approximately four-thirds the size of the input
size_t output_length = ((input_length + 2) / 3) * 4 + 1;
char *encoded_output = (char *)malloc(output_length);
if (!encoded_output) {
fprintf(stderr, "Memory allocation failed\n");
return EXIT_FAILURE;
}
base64_encode((unsigned char *)data, input_length, encoded_output);
printf("Encoded: %s\n", encoded_output);
free(encoded_output);
return EXIT_SUCCESS;
}
Base64 解码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const int decoding_table[256] =
{
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-2, -1 ,-2 , -2 ,-2 , -2 , -2 ,-2 ,
-2 ,-2 ,-2 ,-2 ,-2 , -2 ,-2 ,
... // fill in appropriate values here for each character.
};
void base64_decode(const char *input, unsigned char **output, size_t *output_length) {
// Calculate the output buffer's required size based on the input string's padding and content
...
}
int main() {
const char *encoded_data = "SGVsbG8sIFdvcmxkIQ=="; // Example of an encoded string
unsigned char *decoded_output;
size_t decoded_length;
base64_decode(encoded_data, &decoded_output, &decoded_length);
printf("Decoded: %.*s\n", (int)decoded_length, decoded_output);
free(decoded_output);
return EXIT_SUCCESS;
}
注意:
- 在实际实现中,
decoding_table
的填充需要包含所有字符的映射,以便进行正确的解码。 - 解码函数
base64_decode
中应该处理输入字符串的各种情况,比如可能存在的填充字符 (=
),并正确计算输出长度。 - 此代码仅用于学习目的,实际应用中可以考虑使用成熟的库,如 OpenSSL 等。
内容由零声教学AI助手提供,问题来源于学员提问