Base64 is a binary-to-text encoding scheme that represents binary data in an ASCII string format. It is commonly used to encode binary data, such as images or files, so that it can be transmitted over text-based protocols, such as HTTP, that do not support binary data directly. Base64 encoding converts binary data into a string of ASCII characters, making it safe for transmission over these protocols.
Base64 encoding works by dividing the binary data into groups of 6 bits and representing each group as a single ASCII character. This results in a larger encoded string compared to the original binary data, but it ensures that the encoded data contains only printable ASCII characters, making it suitable for use in text-based contexts.
Examples:
- Encoding a String: The string “Hello, World!” can be encoded in Base64 as “SGVsbG8sIFdvcmxkIQ==“. Each character in the Base64 string represents 6 bits of the original binary data.
- Encoding an Image: Binary image data can be encoded in Base64 and embedded directly into an HTML document using a data URL (e.g.,
<img src="data:image/png;base64,...">
).
Use Case:
// Example: Encoding a string in Base64 using JavaScript
let str = "Hello, World!";
let encoded = btoa(str);
console.log(encoded); // Output: "SGVsbG8sIFdvcmxkIQ=="
In this example, the btoa
function is used in JavaScript to encode the string “Hello, World!” in Base64 format. The resulting Base64-encoded string can be safely transmitted over text-based protocols and decoded back to its original form if needed.