c++ 字符串转base64库
时间: 2025-01-29 13:13:46 浏览: 38
在C++中,将字符串转换为Base64编码可以通过多种库实现。以下是一些常用的库和方法:
1. **OpenSSL库**:
OpenSSL是一个功能强大的开源库,支持多种加密和编码功能,包括Base64编码。
```cpp
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <string>
#include <iostream>
std::string base64_encode(const std::string &in) {
BIO *bio, *b64;
BUF_MEM *bufferPtr;
b64 = BIO_new(BIO_f_base64());
bio = BIO_new(BIO_s_mem());
bio = BIO_push(b64, bio);
BIO_write(bio, in.c_str(), in.length());
BIO_flush(bio);
BIO_get_mem_ptr(bio, &bufferPtr);
BIO_set_close(bio, BIO_NOCLOSE);
BIO_free_all(bio);
return std::string(bufferPtr->data, bufferPtr->length - 1);
}
int main() {
std::string input = "Hello, World!";
std::string encoded = base64_encode(input);
std::cout << encoded << std::endl;
return 0;
}
```
2. **Boost库**:
Boost库提供了多种功能强大的工具,其中也包括Base64编码。
```cpp
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/range/adaptors.hpp>
#include <string>
#include <iostream>
std::string base64_encode(const std::string &in) {
using namespace boost::archive::iterators;
using It = base64_from_binary<transform_width<std::string::const_iterator, 6, 8>>;
auto tmp = std::string(It(in.begin()), It(in.end()));
return tmp.append((3 - in.size() % 3) % 3, '=');
}
int main() {
std::string input = "Hello, World!";
std::string encoded = base64_encode(input);
std::cout << encoded << std::endl;
return 0;
}
```
3. **C++标准库**:
如果不想依赖外部库,可以使用C++标准库自行实现Base64编码。
```cpp
#include <string>
#include <vector>
#include <iostream>
std::string base64_encode(const std::string &in) {
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
std::string ret;
int val = 0;
int valb = -6;
for (unsigned char c : in) {
val = (val << 8) + c;
valb += 8;
while (valb >= 0) {
ret.push_back(base64_chars[(val >> valb) & 0x3F]);
valb -= 6;
}
}
if (valb > -6) ret.push_back(base64_chars[((val << 8) >> (valb + 8)) & 0x3F]);
while (ret.size() % 4) ret.push_back('=');
return ret;
}
int main() {
std::string input = "Hello, World!";
std::string encoded = base64_encode(input);
std::cout << encoded << std::endl;
return 0;
}
```
阅读全文
相关推荐

















