用c语言实现base64编码接口程序
用c语言实现base64编码接口程序
简要介绍base64
Base64 编码是一种常用的编码方式,主要用于将二进制数据转换为可打印的 ASCII 字符集,以便在不支持二进制传输的介质上安全地传输数据。🌟
Base64 编码的特点:
字符集:Base64 使用 64 个字符来表示数据,包括大写和小写字母、数字以及两个额外的符号(通常是 '+' 和 '/')。
编码过程:将输入数据每 3 个字节(24 位)分为一组,然后将这 24 位分为 4 个 6 位的单元,每个单元转换为一个 Base64 字符。
填充:如果输入数据不是 3 字节的整数倍,Base64 会在末尾添加一个或两个 '=' 符号进行填充。
头文件/宏定义
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Base64编码表
全局变量或写在函数内
const char base64_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
函数
// Base64编码函数
void base64_encode(const unsigned char *input, int length, char **output, int*output_length)
{
    *output_length = 4* ((length + 2) / 3); // 计算输出长度
    *output = (char*)malloc(*output_length);
    for (int i = 0, j = 0; i < length; i += 3, j += 4)
    {
        unsigned int triple = (i + 2 < length) ? ((input[i] << 16) | (input[i + 1] << 8) | input[i + 2]) : ((i + 1 < length) ? (input[i] << 16) | (input[i + 1] << 8) : (input[i] << 16));
        (*output)[j] = base64_table[(triple >> 18) & 0x3F];
        (*output)[j + 1] = base64_table[(triple >> 12) & 0x3F];
        (*output)[j + 2] = (i + 1 < length) ? base64_table[(triple >> 6) & 0x3F] : '=';
        (*output)[j + 3] = (i + 2 < length) ? base64_table[triple & 0x3F] : '=';
    }
}
主函数(验证)
int main()
{
    const char *input = "Hello, World!";
    char*output;
    int output_length;
    base64_encode((const unsigned char *)input, strlen(input), &output, &output_length);
    printf("Base64 Encoded: %s\n", output);
    free(output);
    return 0;
}
验证结果
./base64
Base64 Encoded: SGVsbG8sIFdvcmxkIQ==

                
            
        
浙公网安备 33010602011771号