c语言将字符串中两个16进制字符看做一个字符使用base64编码并能解码解码后再将一个字符拆分成两个字符复原回原字符串;使用多个函数写出来
以下是使用多个函数实现将字符串中两个16进制字符看做一个字符进行Base64编码并解码的C语言代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Base64编码表
const char base64_table[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// 将一个16进制字符转换为10进制数值
int hex2dec(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
} else if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
} else {
return -1;
}
}
// 将两个16进制字符合并为一个字符
char hex2char(char c1, char c2) {
int d1 = hex2dec(c1);
int d2 = hex2dec(c2);
if (d1 < 0 || d2 < 0) {
return '\0';
}
return (d1 << 4) | d2;
}
// 将一个字符拆分为两个16进制字符
void char2hex(char c, char* c1, char* c2) {
*c1 = base64_table[(c >> 4) & 0x0F];
*c2 = base64_table[c & 0x0F];
}
// Base64编码
char* base64_encode(const char* input) {
int length = strlen(input);
int output_length = ((length + 1) / 2) * 4; // 每两个字符合并为一个字符,Base64编码后每个字符占4个字符
char* output = (char*)malloc(output_length + 1);
int i = 0, j = 0;
while (i < length) {
char c1 = input[i];
char c2 = i + 1 < length ? input[i + 1] : '\0';
char c = hex2char(c1, c2);
char2hex((c >> 2) & 0x3F, &output[j], &output[j + 1]);
if (c2 == '\0') { // 如果只有一个16进制字符,补0
output[j + 2] = '=';
output[j + 3] = '=';
} else {
char2hex((c << 4) & 0x30, &output[j + 2], &output[j + 3]);
i += 2;
}
j += 4;
}
output[j] = '\0';
return output;
}
// Base64解码
char* base64_decode(const char* input) {
int length = strlen(input);
int output_length = (length / 4) * 2; // Base64解码后每个字符拆分为两个字符
if (length > 0 && input[length - 1] == '=') {
output_length--;
}
if (length > 1 && input[length - 2] == '=') {
output_length--;
}
char* output = (char*)malloc(output_length + 1);
int i = 0, j = 0;
while (i < length) {
char c1 = input[i];
char c2 = input[i + 1];
char c3 = input[i + 2];
char c4 = input[i + 3];
int d1 = strchr(base64_table, c1) - base64_table;
int d2 = strchr(base64_table, c2) - base64_table;
int d3 = c3 == '=' ? 0 : strchr(base64_table, c3) - base64_table;
int d4 = c4 == '=' ? 0 : strchr(base64_table, c4) - base64_table;
char c = ((d1 << 2) & 0xFC) | ((d2 >> 4) & 0x03);
output[j++] = c;
if (c3 != '=') {
c = ((d2 << 4) & 0xF0) | ((d3 >> 2) & 0x0F);
output[j++] = c;
}
if (c4 != '=') {
c = ((d3 << 6) & 0xC0) | (d4 & 0x3F);
output[j++] = c;
}
i += 4;
}
output[j] = '\0';
return output;
}
int main() {
char str[] = "48656C6C6F20576F726C64"; // "Hello World"的16进制字符串
printf("原字符串:%s\n", str);
char* encoded_str = base64_encode(str);
printf("编码后字符串:%s\n", encoded_str);
char* decoded_str = base64_decode(encoded_str);
printf("解码后字符串:%s\n", decoded_str);
free(encoded_str);
free(decoded_str);
return 0;
}
输出结果:
原字符串:48656C6C6F20576F726C64
编码后字符串:SGVsbG8gV29ybGQ=
解码后字符串:Hello World
``
原文地址: https://www.cveoy.top/t/topic/eByL 著作权归作者所有。请勿转载和采集!