C++ 手动实现base64,解码结尾出现多余乱码

C++ 手动实现base64,解码结尾出现多余乱码

具体代码网上有,出现此错误的输出参数为unsigned char *

在最后一位加上结尾符,比如output[end] = ‘\0’;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Base64是一种将二进制数据编码为ASCII字符的方法,常用于网络传输。以下是C++实现Base64解码的步骤: 1. 将Base64编码后的字符串换为对应的二进制数据。 2. 将二进制数据按照每6位一组进行分组,并将每组换为对应的十进制数。 3. 将每个十进制数换为对应的ASCII字符。 4. 将所有的ASCII字符连接起来,即为Base64解码后的字符串。 以下是C++代码实现Base64解码的函数: ```c++ #include <string> #include <vector> std::string base64_decode(const std::string& encoded_string) { const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; std::vector<unsigned char> decoded_data; int i = 0; int j = 0; int in_len = encoded_string.size(); unsigned char char_array_4[4], char_array_3[3]; while (in_len-- && (encoded_string[i] ! '=') && is_base64(encoded_string[i])) { char_array_4[j++] = encoded_string[i]; i++; if (j == 4) { for (j = 0; j < 4; j++) { char_array_4[j] = base64_chars.find(char_array_4[j]); } char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (j = 0; j < 3; j++) { decoded_data.push_back(char_array_3[j]); } j = 0; } } if (j) { for (int i = j; i < 4; i++) { char_array_4[i] = 0; } for (int i = 0; i < 4; i++) { char_array_4[i] = base64_chars.find(char_array_4[i]); } char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (int i = 0; i < j - 1; i++) { decoded_data.push_back(char_array_3[i]); } } return std::string(decoded_data.begin(), decoded_data.end()); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值