Base64 编码器与 Boost





0/5 (0投票)
Base64 编码器与 Boost
最近我一直在寻找一个 Base64 库,然后我想,“我知道,它肯定在 Boost 里面,我有 Boost,而且 Boost 拥有一切。” 结果还真是这样! 某种程度上。 但它有点奇怪,而且不幸的是不完整。
所以让我们来修复它。
首先,我真的不知道如何将这些 Boost 组件连接在一起,所以我在备受喜爱的 StackOverflow(程序员的银河系指南)上快速搜索了一下 得到了以下代码,我对其进行了一些修改
using namespace boost::archive::iterators; typedef insert_linebreaks< // insert line breaks every 76 characters base64_from_binary< // convert binary values to base64 characters transform_width< // retrieve 6 bit integers from a sequence of 8 bit bytes const unsigned char * ,6 ,8 > > ,76 > base64Iterator; // compose all the above operations in to a new iterator
令人作呕,不是吗? 它也不能正常工作。 它只能在您使用的数据是 3 的倍数时工作,所以我们必须自己进行填充。 这是完整的代码:
#include <boost/archive/iterators/base64_from_binary.hpp> #include <boost/archive/iterators/insert_linebreaks.hpp> #include <boost/archive/iterators/transform_width.hpp> namespace Base64Utilities { std::string ToBase64(std::vector<unsigned char> data) { using namespace boost::archive::iterators; // Pad with 0 until a multiple of 3 unsigned int paddedCharacters = 0; while(data.size() % 3 != 0) { paddedCharacters++; data.push_back(0x00); } // Crazy typedef black magic typedef insert_linebreaks< // insert line breaks every 76 characters base64_from_binary< // convert binary values to base64 characters transform_width< // retrieve 6 bit integers from a sequence of 8 bit bytes const unsigned char * ,6 ,8 > > ,76 > base64Iterator; // compose all the above operations in to a new iterator // Encode the buffer and create a string std::string encodedString( base64Iterator(&data[0]), base64Iterator(&data[0] + (data.size() - paddedCharacters))); // Add '=' for each padded character used for(unsigned int i = 0; i < paddedCharacters; i++) { encodedString.push_back('='); } return encodedString; } }
它不是那么优雅,但似乎可以工作。 你能改进这段代码吗? 你能写出解码函数吗? 使用这个优秀的 在线 Base64 转换器来检查你的答案。
请在下方留下你的评论!