查看“C语言实现Base64编码字符串”的源代码
←
C语言实现Base64编码字符串
跳到导航
跳到搜索
因为以下原因,您没有权限编辑本页:
您所请求的操作仅限于该用户组的用户使用:
用户
您可以查看和复制此页面的源代码。
base64_encoder.c<syntaxhighlight lang="c"> #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; } </syntaxhighlight>
返回至
C语言实现Base64编码字符串
。
导航菜单
个人工具
登录
名字空间
页面
讨论
变种
视图
阅读
查看源代码
查看历史
更多
搜索
导航
首页
Spring Boot 2 零基础入门
Spring Cloud
Spring Boot
设计模式之禅
VUE
Vuex
Maven
算法
技能树
Wireshark
IntelliJ IDEA
ElasticSearch
VirtualBox
软考
正则表达式
程序员精讲
软件设计师精讲
初级程序员 历年真题
C
SQL
Java
FFmpeg
Redis
Kafka
MySQL
Spring
Docker
JMeter
Apache
Linux
Windows
Git
ZooKeeper
设计模式
Python
MyBatis
软件
数学
PHP
IntelliJ IDEA
CS基础知识
网络
项目
未分类
MediaWiki
镜像
问题
健身
国债
英语
烹饪
常见术语
MediaWiki帮助
工具
链入页面
相关更改
特殊页面
页面信息