C语言实现Base64编码字符串

来自姬鸿昌的知识库
Jihongchang讨论 | 贡献2025年8月20日 (三) 01:14的版本 (建立内容为“<syntaxhighlight lang="c"> #include <stdio.h> #include <stdlib.h> #include <string.h> // Base64编码表 const char base64_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZa…”的新页面)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)
跳到导航 跳到搜索
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Base64编码表
const char base64_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

// 计算Base64编码后的长度
size_t base64_encoded_length(size_t input_len) {
    return (input_len + 2) / 3 * 4;
}

// 将字符串转换为Base64编码
char* string_to_base64(const unsigned char* input, size_t input_len) {
    // 计算输出缓冲区大小并分配内存
    size_t output_len = base64_encoded_length(input_len);
    char* output = (char*)malloc(output_len + 1); // +1 用于存储终止符
    if (output == NULL) {
        return NULL; // 内存分配失败
    }

    int i, j;
    for (i = 0, j = 0; i < input_len; i += 3, j += 4) {
        // 读取3个字节,不足的用0填充
        unsigned char byte1 = input[i];
        unsigned char byte2 = (i + 1 < input_len) ? input[i + 1] : 0;
        unsigned char byte3 = (i + 2 < input_len) ? input[i + 2] : 0;

        // 将3个8位字节转换为4个6位值
        unsigned int val = (byte1 << 16) | (byte2 << 8) | byte3;

        // 提取每个6位值并映射到Base64字符
        output[j] = base64_chars[(val >> 18) & 0x3F];
        output[j + 1] = base64_chars[(val >> 12) & 0x3F];

        // 处理填充字符'='
        output[j + 2] = (i + 1 < input_len) ? base64_chars[(val >> 6) & 0x3F] : '=';
        output[j + 3] = (i + 2 < input_len) ? base64_chars[val & 0x3F] : '=';
    }

    output[output_len] = '\0'; // 添加字符串终止符
    return output;
}

int main() {
    // 测试示例
    const char* test_strings[] = {
        "Hello, World!",
        "Base64 encoding in C",
        "1234567890",
        "", // 空字符串
        "a", // 长度为1
        "ab", // 长度为2
        "abc", // 长度为3
        "abcd" // 长度为4
    };

    int num_tests = sizeof(test_strings) / sizeof(test_strings[0]);

    for (int i = 0; i < num_tests; i++) {
        const char* input = test_strings[i];
        char* encoded = string_to_base64((const unsigned char*)input, strlen(input));

        if (encoded != NULL) {
            printf("原始字符串: \"%s\"\n", input);
            printf("Base64编码: \"%s\"\n\n", encoded);
            free(encoded); // 释放分配的内存
        }
        else {
            printf("编码失败: 内存分配错误\n");
        }
    }

    return 0;
}