写在前面:这个只是我个人学习base64后的尝试实现,可能会有错误,请注意甄别。
main.cpp
#include <iostream>
#include <string.h>
#include "stdio.h"
#include "base64.h"
using namespace std;
int main()
{
string text = "Hello World!";
string base64 = text2Base64(text);
cout << base64 << endl;
return 0;
}
base64.h
#ifndef __BASE64__
#define __BASE64__
#include <string>
#include <iostream>
using namespace std;
// 字符串转base64
string text2Base64(string text);
// 获取字符串的位
char getBitFromString(string text, int index);
#endif
base64.cpp
#include "base64.h"
char BASE64_TABLE[64] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
char getBitFromString(string text, int index)
{
return (text[index / 8] & (1 << 7 >> (index % 8))) >> (7 - index % 8);
}
string text2Base64(string text)
{
string base64 = "";
char ch = 0;
int textBitLen = 0;
textBitLen = text.size() * 8;
for (int i = 0; i < textBitLen; i += 6)
{
// 判断剩下的还够不够6位
if (textBitLen - i < 6)
break;
ch = 0;
for (int j = 0; j < 6; j++)
{
ch |= getBitFromString(text, i + j) << (5 - j);
}
base64 += BASE64_TABLE[ch];
}
// 判断下是否把text的每一位都处理了
if (text.size() * 8 % 6 != 0)
{
ch = 0;
for (int i = 0; i < text.size() * 8 % 6; i++)
{
ch |= getBitFromString(text, textBitLen / 6 * 6 + i) << (5 - i);
}
base64 += BASE64_TABLE[ch];
}
// 补充末尾的'='
for (int i = 0; i < base64.size() % 4; i++)
{
base64 += '=';
}
return base64;
}
输出
SGVsbG8gV29ybGQh