imradv3 / src /base64 /base64.cpp
fasdfsa's picture
wechat ocr 用于编辑器
6ef0bb6
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
// Base64编码表
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// 检查字符是否是base64字符
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
// 将二进制数据转换为base64字符串
std::string base64_encode(std::string pth_img) {
// 打开二进制文件
std::ifstream file(pth_img, std::ios::binary);
if (!file) {
std::cerr << "无法打开文件: " << pth_img << std::endl;
}
// 读取文件内容到vector
const std::vector<unsigned char> data(
(std::istreambuf_iterator<char>(file)),
(std::istreambuf_iterator<char>())
);
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
int data_size = data.size();
while (data_size--) {
char_array_3[i++] = data[j++];
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_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (i = 0; i < 4; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i) {
for (j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; j < i + 1; j++)
ret += base64_chars[char_array_4[j]];
while (i++ < 3)
ret += '=';
}
return ret;
}
// 将base64字符串转换回二进制数据
std::vector<unsigned char> base64_decode(const std::string& input) {
const std::string BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::vector<int> decode_table(256, -1);
for (int i = 0; i < 64; i++)
decode_table[BASE64_CHARS[i]] = i; // 构建解码表[6,8](@ref)
std::vector<unsigned char> decoded;
int val = 0, bits = -8; // val:24位缓冲区, bits:当前有效位数
for (unsigned char c : input) {
if (c == '=') break; // 遇填充符终止
if (decode_table[c] == -1) continue; // 跳过非法字符
val = (val << 6) + decode_table[c]; // 合并6位数据[6](@ref)
bits += 6;
if (bits >= 0) { // 每凑够8位输出1字节
decoded.push_back((val >> bits) & 0xFF);
bits -= 8;
}
}
return decoded;
}
// std::vector<unsigned char> binary_data = base64_decode(base64_data);
// std::ofstream out_file(output_file, std::ios::binary);
// out_file.write(reinterpret_cast<const char*>(binary_data.data()), binary_data.size());
// out_file.close();