How to Base64 Encode a String

Learn how to Base64 encode any text string. Step-by-step guide with examples in multiple languages, common use cases, and encoding best practices.

Encoding

Detailed Explanation

Base64 encoding converts arbitrary data into a string of printable ASCII characters. When you encode a text string, each character is first converted to its byte representation, and then those bytes are processed in groups of three. Each group of three bytes (24 bits) is split into four 6-bit values, and each 6-bit value is mapped to a character from the Base64 alphabet (A-Z, a-z, 0-9, +, /).

How it works step by step:

  1. Take the input string, for example "Hi".
  2. Convert each character to its ASCII byte value: H = 72, i = 105.
  3. Write out the binary: 01001000 01101001.
  4. Group into 6-bit chunks: 010010 000110 1001. Since the last chunk has only 4 bits, pad it with zeros to make 010010 000110 100100.
  5. Map each 6-bit value to the Base64 alphabet: S, G, k.
  6. Since the original input was 2 bytes (not a multiple of 3), append one = padding character, giving the final result SGk=.

In JavaScript:

const encoded = btoa("Hello, World!");
// Result: "SGVsbG8sIFdvcmxkIQ=="

Common mistake: The btoa() function in browsers only handles Latin-1 characters. If your string contains characters outside the Latin-1 range (like emoji or CJK characters), you must first encode the string to UTF-8 bytes before Base64 encoding. See the Unicode/UTF-8 entry for details on handling this correctly.

Base64 encoding is deterministic, meaning the same input always produces the same output. This makes it reliable for embedding data in text-based formats, but remember it is not compression or encryption -- the encoded output is always about 33% larger than the input.

Use Case

Encoding a username and password pair for HTTP Basic Authentication headers, where the credentials must be transmitted as a single ASCII string.

Try It — Base64 Encoder

Open full tool