base64 算法实现(收集网络中好的代码)
- 第一种 c++实现
const char base64_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string base64_encode(const char* input, int length) {
std::string output;
for (int i = 0; i < length; i += 3) {
int c1 = input[i];
int c2 = i + 1 < length ? input[i + 1] : 0;
int c3 = i + 2 < length ? input[i + 2] : 0;
int index1 = (c1 >> 2) & 0x3f;
int index2 = ((c1 & 0x3) << 4) | ((c2 >> 4) & 0xf);
int index3 = ((c2 & 0xf) << 2) | ((c3 >> 6) & 0x3);
int index4 = c3 & 0x3f;
output += base64_table[index1];
output += base64_table[index2];
output += i + 1 < length ? base64_table[index3] : '=';
output += i + 2 < length ? base64_table[index4] : '=';
}
return output;
}
- 第二种 c语言实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char base64_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
char* base64_encode(const unsigned char* input, size_t input_length) {
size_t output_length = 4 * ((input_length + 2) / 3);
char* encoded_data = (char*)malloc(output_length + 1);
if (encoded_data == NULL) {
return NULL;
}
size_t i, j;
for (i = 0, j = 0; i < input_length;) {
uint32_t octet_a = i < input_length ? input[i++] : 0;
uint32_t octet_b = i < input_length ? input[i++] : 0;
uint32_t octet_c = i < input_length ? input[i++] : 0;
uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
encoded_data[j++] = base64_chars[(triple >> 3 * 6) & 0x3F];
encoded_data[j++] = base64_chars[(triple >> 2 * 6) & 0x3F];
encoded_data[j++] = base64_chars[(triple >> 1 * 6) & 0x3F];
encoded_data[j++] = base64_chars[(triple >> 0 * 6) & 0x3F];
}
// 补充末尾的填充字符 '='
for (size_t i = 0; i < (3 - input_length % 3) % 3; i++) {
encoded_data[output_length - 1 - i] = '=';
}
encoded_data[output_length] = '\0';
return encoded_data;
}
int main() {
unsigned char input[100];
printf("请输入要进行Base64编码的字符串: ");
fgets(input, sizeof(input), stdin);
input[strcspn(input, "\n")] = '\0';
char* encoded = base64_encode(input, strlen(input));
printf("Base64编码结果: %s\n", encoded);
free(encoded);
return 0;
}