Skip to content

Commit

Permalink
Avoid division by 3 on each iteration in encode_base64()
Browse files Browse the repository at this point in the history
  • Loading branch information
dacap committed Aug 24, 2022
1 parent 50409e1 commit b5d92d9
Showing 1 changed file with 5 additions and 1 deletion.
6 changes: 5 additions & 1 deletion base/base64.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -60,25 +60,29 @@ void encode_base64(const char* input, size_t n, std::string& output)
auto outEnd = output.end();
uint8_t next = 0;
size_t i = 0;
size_t j = 0;
for (; i<n; ++i, ++input) {
auto inputValue = *input;
switch (i%3) {
switch (j) {
case 0:
*outIt = base64Char((inputValue & 0b11111100) >> 2);
++outIt;
next |= (inputValue & 0b00000011) << 4;
++j;
break;
case 1:
*outIt = base64Char(((inputValue & 0b11110000) >> 4) | next);
++outIt;
next = (inputValue & 0b00001111) << 2;
++j;
break;
case 2:
*outIt = base64Char(((inputValue & 0b11000000) >> 6) | next);
++outIt;
*outIt = base64Char(inputValue & 0b00111111);
++outIt;
next = 0;
j = 0;
break;
}
}
Expand Down

0 comments on commit b5d92d9

Please sign in to comment.