-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase64.cpp
More file actions
46 lines (45 loc) · 1.23 KB
/
base64.cpp
File metadata and controls
46 lines (45 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include "base64.hpp"
std::string base64_encode(uint8_t const *buf, size_t bufLen)
{
static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string b64;
uint8_t arr3[3];
uint8_t arr4[4];
int i = 0;
while (bufLen--)
{
arr3[i++] = *(buf++);
if (i == 3)
{
arr4[0] = (arr3[0] & 0xfcU) >> 2;
arr4[1] = ((arr3[0] & 0x03U) << 4) | ((arr3[1] & 0xf0U) >> 4);
arr4[2] = ((arr3[1] & 0x0fU) << 2) | ((arr3[2] & 0xc0U) >> 6);
arr4[3] = arr3[2] & 0x3fU;
for (i = 0; i < 4; ++i)
{
b64 += base64_chars[arr4[i]];
}
i = 0;
}
}
if (i != 0)
{
for (int j = i; j < 3; ++j)
{
arr3[j] = 0;
}
arr4[0] = (arr3[0] & 0xfcU) >> 2;
arr4[1] = ((arr3[0] & 0x03U) << 4) | ((arr3[1] & 0xf0U) >> 4);
arr4[2] = ((arr3[1] & 0x0fU) << 2) | ((arr3[2] & 0xc0U) >> 6);
arr4[3] = arr3[2] & 0x3fU;
for (int j = 0; j <= i; ++j)
{
b64 += base64_chars[arr4[j]];
}
while (i++ < 3)
{
b64 += '=';
}
}
return b64;
}