C++——实现base64编码
不废话,直接开整
使用C++的文件操作,读取图片,实现base64编码,编码结果打印到控制台(未实现文件写入),测试可通过👉图片转Base64编码 - 在线工具 - OKTools
代码如下
#include <iostream>
#include <fstream>
#define MAX 1200
using namespace std;
const char *base64_code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
void base64_encode(char *path1) {
unsigned char buffer[MAX];
ifstream file_read;
file_read.open(path1, ios::binary);
while (!file_read.eof()) {
file_read.read((char *) buffer, MAX * sizeof(char));
int num = file_read.gcount();
int index[4];
for (int i = 0; i < num / 3 * 3; i += 3) {
index[0] = buffer[i] >> 2;
index[1] = (buffer[i] & 0x03) << 4 | buffer[i + 1] >> 4;
index[2] = (buffer[i + 1] & 0x0f) << 2 | buffer[i + 2] >> 6;
index[3] = buffer[i + 2] & 0x3f;
for (int j = 0; j < 4; ++j) {
cout << base64_code[index[j]];
}
}
if (num % 3 != 0) {
index[0] = num % 3 == 1 ? buffer[num - 1] >> 2 : buffer[num - 2] >> 2;
index[1] =
num % 3 == 1 ? (buffer[num - 1] & 0x03) << 4 : (buffer[num - 2] & 0x03) << 4 | buffer[num - 1] >> 4;
index[2] = num % 3 == 1 ? 64 : (buffer[num - 1] & 0x0f) << 2;
index[3] = 64;
for (int j = 0; j < 4; ++j) {
cout << base64_code[index[j]];
}
}
}
file_read.close();
}
int main() {
base64_encode("C:\\Users\\LIN\\CLionProjects\\AlgorithmDemo\\demo.png");
return 0;
}
控制台信息如下:
测试结果如下:
|