linux c++将base64封装成类给出实现
以下是一个将base64封装成类的C++实现示例:
#include <iostream>
#include <string>
#include <vector>
class Base64 {
public:
static std::string encode(const std::string& input) {
std::string encodedStr;
std::vector<int> bitStream;
// 将输入字符串转换为二进制流
for (const auto& c : input) {
for (int i = 7; i >= 0; --i) {
bitStream.push_back((c >> i) & 1);
}
}
// 补足二进制流的长度为8的倍数
while (bitStream.size() % 6 != 0) {
bitStream.push_back(0);
}
// 将二进制流转换为base64字符
for (size_t i = 0; i < bitStream.size(); i += 6) {
int decimal = 0;
for (int j = 0; j < 6; ++j) {
decimal += (bitStream[i + j] << (5 - j));
}
encodedStr += base64Chars[decimal];
}
// 补足base64字符串长度为4的倍数
while (encodedStr.size() % 4 != 0) {
encodedStr += '=';
}
return encodedStr;
}
static std::string decode(const std::string& input) {
std::string decodedStr;
std::vector<int> bitStream;
// 将base64字符串转换为二进制流
for (const auto& c : input) {
if (c == '=') {
break;
}
for (int i = 5; i >= 0; --i) {
bitStream.push_back((base64Chars.find(c) >> i) & 1);
}
}
// 将二进制流转换为字符
for (size_t i = 0; i < bitStream.size(); i += 8) {
int decimal = 0;
for (int j = 0; j < 8; ++j) {
decimal += (bitStream[i + j] << (7 - j));
}
decodedStr += static_cast<char>(decimal);
}
return decodedStr;
}
private:
static const std::string base64Chars;
};
const std::string Base64::base64Chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
int main() {
std::string input = "Hello, World!";
std::string encoded = Base64::encode(input);
std::cout << "Encoded: " << encoded << std::endl;
std::string decoded = Base64::decode(encoded);
std::cout << "Decoded: " << decoded << std::endl;
return 0;
}
在上述示例中,Base64类提供了encode和decode静态方法来进行base64编码和解码。encode方法接受一个字符串作为输入并返回base64编码后的字符串。decode方法接受一个base64编码的字符串作为输入并返回解码后的字符串。
该示例使用了一个包含所有base64字符的字符串来进行编码和解码操作。其中,encode方法将输入字符串转换为二进制流,然后将每6位二进制数转换为对应的base64字符。decode方法将base64字符串转换为二进制流,然后将每8位二进制数转换为对应的字符。
运行示例代码会输出以下结果:
Encoded: SGVsbG8sIFdvcmxkIQ==
Decoded: Hello, World!
``
原文地址: https://www.cveoy.top/t/topic/iAAf 著作权归作者所有。请勿转载和采集!