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

Base64 编码是一种常见的将二进制数据转换为可打印 ASCII 字符的方法,常用于在文本协议(如 JSON、HTTP)中安全传输字节流。C++ 没有内置 Base64 支持,但通过位运算和查表法可以轻松实现一个高效且可靠的编码解码器。
Base64 编码原理与字符表
Base64 使用 64 个可打印字符来表示 6 位数据:
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/每 3 个原始字节(24 位)被拆分为 4 个 6 位组,每个组对应一个 Base64 字符。如果输入长度不是 3 的倍数,使用 '=' 进行填充。
例如:
立即学习“C++免费学习笔记(深入)”;
- 3 字节 → 4 Base64 字符
- 1 或 2 字节不足时补 '='
C++ 实现 Base64 编码
编码过程需按 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;}
关键点:
- 用 和 >> 移位合并三字节为 24 位整数
- 用 & 0x3F(即 & 63)取低 6 位
- 根据实际字节数决定是否添加 '=' 填充
C++ 实现 Base64 解码
解码是编码的逆过程,先将字符映射回 6 位值,再组合成原始字节。
int decode_table[256];
void init_decode_table() { for (int i = 0; i (base64_chars[i])] = i; decode_table['='] = 0; // 填充值设为 0,参与计算但不计入输出 }
解码函数:
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;}
注意:
- 提前初始化 decode_table 提高效率
- 检查 '=' 判断有效字符数
- 只将非 '=' 的字符计入最终输出长度
完整使用示例
封装后可在项目中直接调用:
#include iostream> #include// 上述所有函数定义...
int main() { init_decode_table();
std::string text = "Hello World!"; auto encoded = base64_encode(reinterpret_castzuojiankuohaophpcnconst unsigned char*youjiankuohaophpcn(text.data()), text.size()); auto decoded = base64_decode(encoded); std::string roundtrip(decoded.begin(), decoded.end()); std::cout zuojiankuohaophpcnzuojiankuohaophpcn "Encoded: " zuojiankuohaophpcnzuojiankuohaophpcn encoded zuojiankuohaophpcnzuojiankuohaophpcn "\n"; std::cout zuojiankuohaophpcnzuojiankuohaophpcn "Decoded: " zuojiankuohaophpcnzuojiankuohaophpcn roundtrip zuojiankuohaophpcnzuojiankuohaophpcn "\n"; return 0;
}
输出:
Encoded: SGVsbG8gV29ybGQh Decoded: Hello World!基本上就这些。核心是理解 3 字节 ↔ 4 字符的转换逻辑,配合位运算精确提取数据段。这种实现轻量、无依赖,适合嵌入式或性能敏感场景。









