Skip to content
Encode: 3 Bytes to 4 Chars
step 1/5

Reading — step 1 of 5

Read

~1 min readEncoding

Encode: 3 Bytes to 4 Chars

Group input bytes into chunks of 3 = 24 bits. Split into 4 chunks of 6 bits → 4 base64 chars.

Input bytes:    "Hel"  =  H        e        l
                          01001000 01100101 01101100

Pack as 24-bit:  010010 000110 010101 101100
                 ↓      ↓      ↓      ↓
                 18     6      21     44
                 S      G      V      s

Implementation:

python

If the input length isn't a multiple of 3, pad with zero bytes when computing the values, then replace the last 1 or 2 output chars with =:

Input "Hi" (2 bytes) → 3-byte block "Hi\0" → 4 chars → replace last char with '='
                                                    → "SGk="
Input "H"  (1 byte)  → 3-byte block "H\0\0"  → 4 chars → replace last 2 with '=='
                                                    → "SA=="

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…