![](https://csdnimg.cn/release/download_crawler_static/16820934/bg6.jpg)
from the left determine the first character, the next 6 bits the second character and so
forth.
Example 2.1.
Suppose that we need to encode the three byte values 71, 73, 70. We
construct four 6-bit values out of these four bytes:
— 71 ÷ 4 = 17,
— ((71 × 16) mod 64) + (73 ÷ 16) = 52,
— ((73 × 4) mod 64) + (70 ÷ 64) = 37
— and 70 mod 64 = 6.
We then look-up the resulting 6-bit values 17, 52, 37, 6 in Table I to get the ASCII
characters
R
,
0
,
l
,
G
. The string
R0lG
is the base64-encoded version of the three input
bytes 71, 73, 70.
One of the fastest encoder [Galbreath 2016] (used by the Google Chrome browser)
optimizes the main loop of Algorithm 1 by using several 256-byte arrays. One 256-byte
array represents
x → B(x ÷ 4)
, whereas another represents
x → B(x mod 64)
. This
saves a few operations at the expense of a slightly increased memory usage:
—
instead of computing
s
i
÷ 4
and then looking up the resulting index in a table, one can
seek directly
s
i
in a larger table, saving the cost of the division by 4 (which can be
implemented as a shift);
—
instead of computing
s
i+2
mod 64
before looking up the result in a table, we can seek
s
i+2
directly in a larger table, saving the cost of the modulo reduction (which can be
implemented with a bitwise AND).
Using additional memory to save a few arithmetic and logical operations may improve
the performance.
2.3. Efficient Scalar Decoding
We assume that the input base64 data is encoded in ASCII or some ASCII superset
such as UTF-8 or ISO 8859-1. In such cases, any non-ASCII character should trigger
an error. If there are white-space characters (e.g., ’ ’, ’
\n
’ or ’
\r
’), then they must be
removed prior to decoding (see Appendix B).
Algorithm 2 illustrates a decoding procedure. The main loop of the algorithm consists
of two steps, we first map ASCII characters to 6-bit integer values:
— a ← A(C
i
),
— b ← A(C
i+1
),
— c ← A(C
i+2
),
— d ← A(C
i+3
).
And then we compute the three output byte values:
— (a × 4) + (b ÷ 16),
— (b × 16) mod 256 + (c ÷ 4),
— (c × 64) mod 256 + d.
The function A can be implemented as a table lookup.
Example 2.2.
Let us consider the following base64 code
R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=
. It represents a small gif
image. To decode it, we may look up each character for the base64 code (except the
terminating ’
=
’) in Table I and map it to its corresponding value in
[0, 64)
: 17, 52, 37, 6,
14, 3, 37, 33, 0, 16, 0, 1, 0, 8, 0, 0, 0, 15, 63, 63, 63, 48, 0, 0, 0, 2, 48, 0, 0, 0, 0, 0, 0, 16, 0,
1, 0, 0, 0, 2, 0, 36, 16, 1, 0, 3, 44. Then we take each block of 4 consecutive values
a, b, c, d
6