C语言base64函数
时间: 2023-11-11 16:52:59 浏览: 148
C语言中没有内置的base64函数,需要自己实现。
以下是一个简单的实现:
```
#include <stdio.h>
#include <string.h>
static const char base64_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int base64_encode(const unsigned char *src, size_t len, char *dst, size_t dst_len)
{
size_t i, j;
unsigned char buf[4];
int padding = 0;
for (i = 0, j = 0; i < len; i += 3, j += 4) {
buf[0] = src[i];
buf[1] = (i + 1 < len) ? src[i + 1] : 0;
buf[2] = (i + 2 < len) ? src[i + 2] : 0;
dst[j] = base64_table[buf[0] >> 2];
dst[j + 1] = base64_table[((buf[0] & 0x03) << 4) | (buf[1] >> 4)];
dst[j + 2] = (i + 1 < len) ? base64_table[((buf[1] & 0x0f) << 2) | (buf[2] >> 6)] : '=';
dst[j + 3] = (i + 2 < len) ? base64_table[buf[2] & 0x3f] : '=';
if (dst[j + 2] == '=')
padding++;
if (dst[j + 3] == '=')
padding++;
}
dst[j] = '\0';
return padding;
}
int base64_decode(const char *src, size_t len, unsigned char *dst, size_t dst_len)
{
size_t i, j;
unsigned char buf[4];
int padding = 0;
for (i = 0, j = 0; i < len; i += 4, j += 3) {
buf[0] = (src[i] >= 'A' && src[i] <= 'Z') ? src[i] - 'A' :
(src[i] >= 'a' && src[i] <= 'z') ? src[i] - 'a' + 26 :
(src[i] >= '0' && src[i] <= '9') ? src[i] - '0' + 52 :
(src[i] == '+') ? 62 :
(src[i] == '/') ? 63 : -1;
buf[1] = (src[i + 1] >= 'A' && src[i + 1] <= 'Z') ? src[i + 1] - 'A' :
(src[i + 1] >= 'a' && src[i + 1] <= 'z') ? src[i + 1] - 'a' + 26 :
(src[i + 1] >= '0' && src[i + 1] <= '9') ? src[i + 1] - '0' + 52 :
(src[i + 1] == '+') ? 62 :
(src[i + 1] == '/') ? 63 : -1;
buf[2] = (src[i + 2] >= 'A' && src[i + 2] <= 'Z') ? src[i + 2] - 'A' :
(src[i + 2] >= 'a' && src[i + 2] <= 'z') ? src[i + 2] - 'a' + 26 :
(src[i + 2] >= '0' && src[i + 2] <= '9') ? src[i + 2] - '0' + 52 :
(src[i + 2] == '+') ? 62 :
(src[i + 2] == '/') ? 63 : -1;
buf[3] = (src[i + 3] >= 'A' && src[i + 3] <= 'Z') ? src[i + 3] - 'A' :
(src[i + 3] >= 'a' && src[i + 3] <= 'z') ? src[i + 3] - 'a' + 26 :
(src[i + 3] >= '0' && src[i + 3] <= '9') ? src[i + 3] - '0' + 52 :
(src[i + 3] == '+') ? 62 :
(src[i + 3] == '/') ? 63 : -1;
if (buf[0] == -1 || buf[1] == -1 || buf[2] == -1 || buf[3] == -1)
return -1;
dst[j] = (buf[0] << 2) | (buf[1] >> 4);
dst[j + 1] = (buf[1] << 4) | (buf[2] >> 2);
dst[j + 2] = (buf[2] << 6) | buf[3];
if (src[i + 2] == '=')
padding++;
if (src[i + 3] == '=')
padding++;
}
return j - padding;
}
```
其中,`base64_encode`函数用于将二进制数据编码为base64字符串,`base64_decode`函数用于将base64字符串解码为二进制数据。这两个函数都接受指向源数据和目标数据的指针,以及数据长度和目标缓冲区长度。如果目标缓冲区长度不足以容纳编码/解码结果,则返回-1。在编码时,函数还会返回填充字符的数量,以便在解码时正确处理。
阅读全文