Base64编码将每3字节二进制数据拆分为4个6位组,对应64字符表中的可打印字符,不足时用'='填充;C++通过位运算和查表实现高效编解码,适用于文本协议中安全传输字节流。

Base64 编码是一种常见的将二进制数据转换为可打印 ASCII 字符的方法,常用于在文本协议(如 JSON、HTTP)中安全传输字节流。C++ 没有内置 Base64 支持,但通过位运算和查表法可以轻松实现一个高效且可靠的编码解码器。
Base64 使用 64 个可打印字符来表示 6 位数据:
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/每 3 个原始字节(24 位)被拆分为 4 个 6 位组,每个组对应一个 Base64 字符。如果输入长度不是 3 的倍数,使用 '=' 进行填充。
例如:
立即学习“C++免费学习笔记(深入)”;
编码过程需按 3 字节一组处理,利用位移和掩码提取 6 位数据。
const char* base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
编码函数示例:
std::string base64_encode(const unsigned char* data, size_t len) { std::string result; result.reserve((len + 2) / 3 * 4);for (size_t i = 0; i < len; i += 3) {
// 取三个字节(可能越界)
unsigned int n = 0;
int num_bytes = 0;
n |= (i < len ? data[i] : 0) << 16; num_bytes++;
n |= (i + 1 < len ? data[i + 1] : 0) << 8; num_bytes++;
n |= (i + 2 < len ? data[i + 2] : 0); num_bytes++;
// 提取四个 6 位组
result += base64_chars[(n >> 18) & 0x3F];
result += base64_chars[(n >> 12) & 0x3F];
result += (num_bytes > 1) ? base64_chars[(n >> 6) & 0x3F] : '=';
result += (num_bytes > 2) ? base64_chars[n & 0x3F] : '=';
}
return result;}
关键点:
解码是编码的逆过程,先将字符映射回 6 位值,再组合成原始字节。
int decode_table[256];
void init_decode_table() {
for (int i = 0; i < 256; ++i) decode_table[i] = -1;
for (int i = 0; i < 64; ++i)
decode_table[static_cast
解码函数:
std::vectorfor (size_t i = 0; i < str.size(); i += 4) {
unsigned int n = 0;
n |= decode_table[str[i]] << 18;
n |= decode_table[str[i + 1]] << 12;
n |= (i + 2 < str.size() && str[i + 2] != '=') ? decode_table[str[i + 2]] << 6 : 0;
n |= (i + 3 < str.size() && str[i + 3] != '=') ? decode_table[str[i + 3]] : 0;
result.push_back((n >> 16) & 0xFF);
if (i + 2 < str.size() && str[i + 2] != '=') result.push_back((n >> 8) & 0xFF);
if (i + 3 < str.size() && str[i + 3] != '=') result.push_back(n & 0xFF);
}
return result;}
注意:
封装后可在项目中直接调用:
#include <iostream> #include <string> #include <vector>// 上述所有函数定义...
int main() { init_decode_table();
std::string text = "Hello World!"; auto encoded = base64_encode(reinterpret_cast<const unsigned char*>(text.data()), text.size()); auto decoded = base64_decode(encoded); std::string roundtrip(decoded.begin(), decoded.end()); std::cout << "Encoded: " << encoded << "\n"; std::cout << "Decoded: " << roundtrip << "\n"; return 0;
}
输出:
Encoded: SGVsbG8gV29ybGQh Decoded: Hello World!基本上就这些。核心是理解 3 字节 ↔ 4 字符的转换逻辑,配合位运算精确提取数据段。这种实现轻量、无依赖,适合嵌入式或性能敏感场景。
以上就是C++怎么实现一个Base64编码解码器_C++数据编码与位运算实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号