What is Base64 Encoding?
Base64 is a group of binary-to-text encoding schemes defined in IETF RFC 4648. It represents binary data using an alphabet of 64 ASCII characters: uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), and the symbols + and /.
When transferring data across systems designed historically for 7-bit ASCII text (such as email systems using SMTP, or HTTP header fields), raw binary bytes can easily become corrupted by translation gateways. Base64 guarantees safe, unmodified transmission by converting every 3 bytes (24 bits) into 4 printable ASCII characters (6 bits each).
Mathematical Operation: How Base64 Works
The conversion process follows a systematic mathematical grouping:
- Take three 8-bit bytes of input (total 24 bits):
[Byte 1] [Byte 2] [Byte 3]. - Split these 24 bits into four 6-bit chunks:
[Chunk 1] [Chunk 2] [Chunk 3] [Chunk 4]. - Each 6-bit integer (range 0 to 63) maps directly to the RFC 4648 index table (
0 = 'A',26 = 'a',52 = '0',62 = '+',63 = '/'). - Padding: If the input has only 1 remaining byte, 2 padding characters (
==) are appended. If 2 bytes remain, 1 padding character (=) is appended.
Because every 3 bytes expand into 4 characters, Base64 introduces an approximate 33% data size overhead.
Code Integration Examples
Encoding & Decoding UTF-8 in Modern JavaScript
// Safe UTF-8 Base64 Encoding
function utf8ToBase64(text) {
return btoa(unescape(encodeURIComponent(text)));
}
// Safe UTF-8 Base64 Decoding
function base64ToUtf8(base64String) {
return decodeURIComponent(escape(atob(base64String)));
}
Encoding & Decoding in Python 3
import base64
# Encoding UTF-8 string to Base64
raw_text = "Hello, World! 🚀"
encoded_bytes = base64.b64encode(raw_text.encode("utf-8"))
base64_str = encoded_bytes.decode("ascii")
print("Encoded:", base64_str)
# Decoding Base64 back to UTF-8
decoded_bytes = base64.b64decode(base64_str.encode("ascii"))
print("Decoded:", decoded_bytes.decode("utf-8"))