-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbase64.hpp
54 lines (43 loc) · 1.37 KB
/
base64.hpp
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
47
48
49
50
51
52
53
54
#pragma once
#include <string>
namespace ws_client
{
using std::string;
/**
* Base64 encodes binary data as string.
*/
inline string base64_encode(const unsigned char* data, const size_t len)
{
static constexpr char encode_table[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
string encoded;
encoded.reserve(((len + 2) / 3) * 4);
for (size_t i = 0; i < len; i += 3)
{
unsigned int octet_a = i < len ? data[i] : 0;
unsigned int octet_b = i + 1 < len ? data[i + 1] : 0;
unsigned int octet_c = i + 2 < len ? data[i + 2] : 0;
unsigned int triple = (octet_a << 16) + (octet_b << 8) + octet_c;
encoded.push_back(encode_table[(triple >> 18) & 0x3F]);
encoded.push_back(encode_table[(triple >> 12) & 0x3F]);
if (i + 1 < len)
encoded.push_back(encode_table[(triple >> 6) & 0x3F]);
else
encoded.push_back('=');
if (i + 2 < len)
encoded.push_back(encode_table[triple & 0x3F]);
else
encoded.push_back('=');
}
return encoded;
}
/**
* Base64 encodes binary data as string.
*/
inline string base64_encode(const string& str)
{
const unsigned char* data = reinterpret_cast<const unsigned char*>(str.data());
const size_t len = str.size();
return base64_encode(data, len);
}
} // namespace ws_client