我们中的许多人在某个时间点偶然发现了用 Base64 编码的文件或字符串,但不知道从哪里开始。在这种情况下,拥有一个有效的 C 代码片段来解码此类消息会有所帮助。
René Nyffenegger 编写了一个实现,该实现采用二进制数据指针及其大小,并将原始数据转换为 std::string与相应的 Base64 编码数据。提供的解决方案包括一个头文件(base64.h)和一个源文件(base64.cpp)。
下面是优化后的base64.h头文件:
#ifndef _BASE64_H_ #define _BASE64_H_ #include <vector> #include <string> typedef unsigned char BYTE; std::string base64_encode(BYTE const* buf, unsigned int bufLen); std::vector<byte> base64_decode(std::string const&); #endif</byte></string></vector>
这是修改后的base64.cpp源文件:
#include "base64.h" #include <iostream> static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; static inline bool is_base64(BYTE c) { return (isalnum(c) || (c == '+') || (c == '/')); } std::string base64_encode(BYTE const* buf, unsigned int bufLen) { std::string ret; int i = 0; int j = 0; BYTE char_array_3[3]; BYTE char_array_4[4]; while (bufLen--) { char_array_3[i++] = *(buf++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) > 4); char_array_4[2] = ((char_array_3[1] & 0x0f) > 6); char_array_4[3] = char_array_3[2] & 0x3f; for(i = 0; (i '; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) > 4); char_array_4[2] = ((char_array_3[1] & 0x0f) > 6); char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0; (j base64_decode(std::string const& encoded_string) { int in_len = encoded_string.size(); int i = 0; int j = 0; int in_ = 0; BYTE char_array_4[4], char_array_3[3]; std::vector<byte> ret; while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { char_array_4[i++] = encoded_string[in_]; in_++; if (i ==4) { for (i = 0; i > 4);</byte></iostream>
以上是如何在 C 中解码 Base64 字符串?的详细内容。更多信息请关注PHP中文网其他相关文章!