c++实现string转base64编码

写在前面:这个只是我个人学习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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值