Skip to content

Commit

Permalink
Fix base64 encoding when char is signed (#279)
Browse files Browse the repository at this point in the history
**Public-Facing Changes**
Fixed a base64 encoding issue in the C++ example_server.


**Description**
Fixes #278
  • Loading branch information
jtbandes authored Nov 23, 2022
1 parent 29064f7 commit c88a223
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions cpp/examples/example_server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,22 +18,25 @@ static uint64_t nanosecondsSinceEpoch() {

// Adapted from:
// https://gist.github.com/tomykaira/f0fd86b6c73063283afe550bc5d77594
// https://github.com/protocolbuffers/protobuf/blob/01fe22219a0312b178a265e75fe35422ea6afbb1/src/google/protobuf/compiler/csharp/csharp_helpers.cc
static std::string Base64Encode(std::string_view data) {
// https://github.com/protocolbuffers/protobuf/blob/01fe22219a0312b178a265e75fe35422ea6afbb1/src/google/protobuf/compiler/csharp/csharp_helpers.cc#L346
static std::string Base64Encode(std::string_view input) {
constexpr const char ALPHABET[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string result;
// Every 3 bytes of data yields 4 bytes of output
result.reserve((data.size() + (3 - 1 /* round up */)) / 3 * 4);
result.reserve((input.size() + (3 - 1 /* round up */)) / 3 * 4);

// Unsigned values are required for bit-shifts below to work properly
const unsigned char* data = reinterpret_cast<const unsigned char*>(input.data());

size_t i = 0;
for (; i + 2 < data.size(); i += 3) {
for (; i + 2 < input.size(); i += 3) {
result.push_back(ALPHABET[data[i] >> 2]);
result.push_back(ALPHABET[((data[i] & 0b11) << 4) | (data[i + 1] >> 4)]);
result.push_back(ALPHABET[((data[i + 1] & 0b1111) << 2) | (data[i + 2] >> 6)]);
result.push_back(ALPHABET[data[i + 2] & 0b111111]);
}
switch (data.size() - i) {
switch (input.size() - i) {
case 2:
result.push_back(ALPHABET[data[i] >> 2]);
result.push_back(ALPHABET[((data[i] & 0b11) << 4) | (data[i + 1] >> 4)]);
Expand Down

0 comments on commit c88a223

Please sign in to comment.