C++20 Base64 编码解码:使用 std::ranges 实现
C++20 中提供了 std::base64 编解码函数,可以方便地实现 base64 编解码。
编码示例:
#include <iostream>
#include <string>
#include <string_view>
#include <algorithm>
#include <iterator>
#include <vector>
int main()
{
std::string_view str = 'Hello, world!';
std::vector<char> encoded(std::size(str) * 2);
auto it = std::ranges::begin(encoded);
it = std::ranges::transform(str, it, [](char c) { return std::to_integer<unsigned char>(c); });
encoded.resize(std::ranges::distance(std::ranges::begin(encoded), it));
encoded.resize((encoded.size() + 2) / 3 * 4);
std::ranges::encode_base64(encoded, str);
std::cout << std::string_view(std::data(encoded), std::size(encoded)) << '\n';
}
解码示例:
#include <iostream>
#include <string>
#include <string_view>
#include <algorithm>
#include <iterator>
#include <vector>
int main()
{
std::string_view encoded = 'SGVsbG8sIHdvcmxkIQ==';
std::vector<char> decoded(std::size(encoded));
auto it = std::ranges::decode_base64(decoded, encoded);
decoded.resize(std::ranges::distance(std::ranges::begin(decoded), it));
std::cout << std::string_view(std::data(decoded), std::size(decoded)) << '\n';
}
原文地址: https://www.cveoy.top/t/topic/lEW4 著作权归作者所有。请勿转载和采集!