Does anyone know how to decode and encode a string in Base64 using Base64?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Base64 encoding is a widely-used technique for converting binary data into a text format, making it easier to transmit such data over media that are designed to handle text. This method is commonly used in various applications, such as attaching files in emails or embedding image data within HTML or CSS. Understanding how to decode and encode a string in Base64 is crucial for developers working with data transmission.
What is Base64 Encoding?
Base64 is a binary-to-text encoding scheme that translates binary data into a radix-64 representation. The encoding process is simple yet effective: it divides the input data into blocks of three bytes (24 bits) and represents each block as four printable ASCII characters. This ensures that the resulting text is safe to transmit over channels that cannot handle binary data directly.
Base64 Character Set
The Base64 character set consists of 64 characters:
- 26 uppercase letters: A–Z
- 26 lowercase letters: a–z
- 10 digits: 0–9
- 2 special symbols: + and /
The "=" symbol is used as a padding character to ensure the output is a multiple of 4 characters long.
Encoding a String in Base64
To encode a string in Base64, the following steps are typically followed:
- Convert the Input to Binary: Convert each character of the input string to its binary representation.
- Group Binary Data: Divide the binary data into chunks of 24 bits (3 bytes).
- Convert to Base64 Segments: For each 24-bit segment, divide it into four 6-bit pieces. Each 6-bit piece is then mapped to one Base64 character using the Base64 index table.
- Add Padding if Necessary: If the number of bytes in the input is not a multiple of 3, pad the input with zeros. Correspondingly, add one or two "=" characters at the end of the Base64 string to reflect the padding.
Encoding Example
Let's encode the string "Man" as an example:
- ASCII Representation: M = 77, a = 97, n = 110
- Binary Representation: 77 = 01001101, 97 = 01100001, 110 = 01101110
Combine the binary representations:
- 19 (010011) = T
- 22 (010110) = W
- 5 (000101) = F
- 46 (101110) = u
- Convert each character to its 6-bit binary equivalent:
- T = 19 = 010011
- W = 22 = 010110
- F = 5 = 000101
- u = 46 = 101110
- 01001101 = 77 = M
- 01100001 = 97 = a
- 01101110 = 110 = n

