您好,登錄后才能下訂單哦!
在C語言中,實現Base64編碼和解碼可以通過以下步驟進行:
以下是一個簡單的示例:
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
// Base64字符映射表
const char *base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// Base64編碼函數
char *base64_encode(const unsigned char *input, int length) {
int i, j;
int encoded_length = 4 * ((length + 2) / 3);
char *encoded = (char *)malloc(encoded_length + 1);
if (encoded == NULL) return NULL;
for (i = 0, j = 0; i< length;) {
int octet_a = i< length ? input[i++] : 0;
int octet_b = i< length ? input[i++] : 0;
int octet_c = i< length ? input[i++] : 0;
int triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
encoded[j++] = base64_chars[(triple >> 18) & 0x3F];
encoded[j++] = base64_chars[(triple >> 12) & 0x3F];
encoded[j++] = base64_chars[(triple >> 6) & 0x3F];
encoded[j++] = base64_chars[(triple >> 0) & 0x3F];
}
for (i = 0; i < (3 - (length % 3)) % 3; i++) {
encoded[encoded_length - 1 - i] = '=';
}
encoded[encoded_length] = '\0';
return encoded;
}
// Base64解碼函數
unsigned char *base64_decode(const char *input, int *output_length) {
int i, j;
int decoded_length = strlen(input) * 3 / 4;
unsigned char *decoded = (unsigned char *)malloc(decoded_length + 1);
if (decoded == NULL) return NULL;
for (i = 0, j = 0; i < strlen(input);) {
int sextet_a = i < strlen(input) ? strchr(base64_chars, input[i++]) - base64_chars : 0;
int sextet_b = i < strlen(input) ? strchr(base64_chars, input[i++]) - base64_chars : 0;
int sextet_c = i < strlen(input) ? strchr(base64_chars, input[i++]) - base64_chars : 0;
int sextet_d = i < strlen(input) ? strchr(base64_chars, input[i++]) - base64_chars : 0;
int triple = (sextet_a << 18) + (sextet_b << 12) + (sextet_c << 6) + sextet_d;
if (j < decoded_length) decoded[j++] = (triple >> 16) & 0xFF;
if (j < decoded_length) decoded[j++] = (triple >> 8) & 0xFF;
if (j < decoded_length) decoded[j++] = (triple >> 0) & 0xFF;
}
while (decoded[--j] == '=') {
decoded_length--;
}
decoded[decoded_length] = '\0';
*output_length = decoded_length;
return decoded;
}
int main() {
const char *input = "Hello, World!";
int length = strlen(input);
// Base64編碼
char *encoded = base64_encode((unsigned char *)input, length);
printf("Base64編碼: %s\n", encoded);
// Base64解碼
int output_length;
unsigned char *decoded = base64_decode(encoded, &output_length);
printf("Base64解碼: %.*s\n", output_length, decoded);
free(encoded);
free(decoded);
return 0;
}
這個示例中,我們首先定義了一個Base64字符映射表,然后實現了Base64編碼和解碼函數。在main
函數中,我們對一個字符串進行編碼和解碼操作,并輸出結果。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。