Base64 encode/decode · Guide

Base64 to Text File: Saving Decoded Output Correctly

Writing decoded Base64 to a text file introduces two choices Base64 itself does not record: which character encoding to write, and which line endings to use. Getting either wrong corrupts the result silently.

Decode, then write

On the command line the redirect does the work and no interpretation happens at all — which is the safest default:

Shell
base64 -d payload.b64 > output.txt

# verify it really is text before assuming
file output.txt
head -c 64 output.txt | xxd

file inspects the content and tells you what you actually decoded. It is worth the extra second — Base64 carries no type information, so a payload you assumed was text may be a ZIP.

Encoding and line endings

Write UTF-8 unless something requires otherwise, and state it explicitly rather than relying on a platform default:

Python
# Python — newline='' prevents line-ending translation
import base64, pathlib
data = base64.b64decode(payload)
pathlib.Path('output.txt').write_text(data.decode('utf-8'), encoding='utf-8', newline='')

On Windows, opening a file in text mode rewrites \n as \r\n. That changes the bytes, so a checksum of the decoded file will no longer match. Write in binary mode when the bytes must be preserved exactly.

A worked example

The round trip, so you can confirm a pipeline end to end:

Shell
printf %s 'Hello, world!' | base64      # SGVsbG8sIHdvcmxkIQ==
printf %s 'SGVsbG8sIHdvcmxkIQ==' | base64 -d   # Hello, world!

If your tooling produces SGVsbG8sIHdvcmxkIQo= instead, the trailing o= is an appended newline from echo. That single byte is the most common discrepancy in Base64 debugging.

When not to write text

If the decoded bytes are an image, an archive or a PDF, writing them through any text path will corrupt them. Write binary and give the file the right extension — Base64 does not record either.

Check the first bytes if unsure: %PDF for PDF, PK for ZIP-based formats, \x89PNG for PNG, \x1f\x8b for gzip.

Frequently asked questions

Why does my saved file have the wrong characters?

It was written with the wrong encoding. Decode the bytes as UTF-8 and write as UTF-8.

Why does the checksum change after saving?

Line-ending translation in text mode. Write in binary mode to preserve bytes exactly.

How do I know the payload is text at all?

Decode to a file and run "file" on it, or inspect the first bytes in hex for a known signature.

Ready to try it?

Open the free browser-based Base64 encode/decode and apply what you just read — no sign-up, runs locally.

Open the Base64 encode/decode tool