Base64 is a popular encoding scheme used to represent binary data in a text format. It’s commonly used in web development, data transmission, and cryptography to encode binary data into a string of readable characters. This ensures compatibility across systems that may not support raw binary formats.
Base64 encoding takes raw binary data or text and transforms it into a readable string format using 64 characters:
+
and /
The encoded string often includes =
as padding at the end to ensure its length is a multiple of 4. For example, encoding the text "Hello, World!" produces the Base64 string: SGVsbG8sIFdvcmxkIQ==
Base64 decoding reverses the process, converting the encoded string back into its original binary or text format.
This ensures the data is restored to its original form, whether it’s a file, image, or plain text. For example, decoding SGVsbG8sIFdvcmxkIQ==
results in: Hello, World!
If you're a developer, JavaScript provides built-in methods for Base64 encoding and decoding: btoa()
and atob()
.
btoa()
The btoa()
function converts a string to Base64 format. Example:
const text = "Hello, World!"; const encoded = btoa(text); console.log(encoded); // Output: "SGVsbG8sIFdvcmxkIQ=="
atob()
The atob()
function decodes a Base64 string back into its original format. Example:
const base64Text = "SGVsbG8sIFdvcmxkIQ=="; const decoded = atob(base64Text); console.log(decoded); // Output: "Hello, World!"
For non-ASCII characters, use encodeURIComponent()
and decodeURIComponent()
for proper handling. Example:
const text = "Привет"; // A string with non-ASCII characters const encoded = btoa(unescape(encodeURIComponent(text))); console.log(encoded); // Encodes properly const decoded = decodeURIComponent(escape(atob(encoded))); console.log(decoded); // Decodes back to the original string