DEV Community

meng meng
meng meng

Posted on Originally published at meng4099244-ship-it.github.io

Binary to Text Without the Garbage: Decoding a UTF-8 Dump in Python 3.11, Node 22 and the Browser

Binary to Text Without the Garbage: Decoding a UTF-8 Dump in Python 3.11, Node 22 and the Browser

Last month I was digging through a UART capture from an ESP32 board. The logging tool had already turned the raw bytes into binary for me, so my terminal showed lines like this:

01001000 01101001 00100001
Enter fullscreen mode Exit fullscreen mode

That one decodes to Hi!. The line below it did not cooperate:

11000011 10101001
Enter fullscreen mode Exit fullscreen mode

Two bytes, three decoders, three different answers. One printed é, one printed é, one just gave up. Binary strings like these show up more often than you'd think: UART captures, embedded firmware logs, classroom assignments, hex editors that export in base 2, and the occasional database dump where someone stored text as literal 0101 strings. They all ask the same question: which bytes are these, and what text do they encode?

This post is the set of notes I wish I'd had that afternoon: three reliable ways to convert binary back to text, and the three traps that cost me an hour.

Method 1: Python 3.11, my default

Here is the version I keep in my scratch file. Tested on Python 3.11.1 on Ubuntu 22.04.

# binary_to_text.py — Python 3.11.1
def binary_to_text(binary: str) -> str:
    cleaned = "".join(binary.split())          # tolerate spaces and newlines
    if len(cleaned) % 8 != 0:
        raise ValueError(f"not a whole number of bytes: {len(cleaned)} bits")
    chunks = [cleaned[i:i+8] for i in range(0, len(cleaned), 8)]
    raw = bytes(int(c, 2) for c in chunks)
    return raw.decode("utf-8")                 # the whole trick lives on this line

print(binary_to_text("01001000 01101001 00100001"))
# Hi!
print(binary_to_text("11000011 10101001"))
# é
Enter fullscreen mode Exit fullscreen mode

The decode call is where I first went wrong. My initial draft used raw.decode("latin-1") because an old Stack Overflow answer said it "never fails". It never fails, and it never tells you it mangled anything:

b"\xc3\xa9".decode("latin-1")   # 'é'
b"\xc3\xa9".decode("utf-8")     # 'é'
Enter fullscreen mode Exit fullscreen mode

Two bytes became two characters. If your output shows one accented letter as two strange ones, that is UTF-8 being read as latin-1 or cp1252. The decode() method and error handlers are documented in the Python docs on bytes.decode.

Going the other direction is symmetric, and it is the part I use more often when embedding test fixtures:

def text_to_binary(text: str) -> str:
    return " ".join(f"{b:08b}" for b in text.encode("utf-8"))

print(text_to_binary("Hi!"))
# 01001000 01101001 00100001
Enter fullscreen mode Exit fullscreen mode

Method 2: Node.js 22 for the frontend folks

Same idea, different runtime. Tested on Node v22.13.0.

// bin.js — Node v22.13.0
function binaryToText(binary) {
  const bits = binary.replace(/\s+/g, "");
  if (bits.length % 8 !== 0) throw new Error(`bad length: ${bits.length} bits`);
  const bytes = Uint8Array.from(bits.match(/.{8}/g).map((c) => parseInt(c, 2)));
  return new TextDecoder("utf-8").decode(bytes);
}

console.log(binaryToText("01001000 01101001 00100001")); // Hi!
console.log(binaryToText("11000011 10101001"));          // é
Enter fullscreen mode Exit fullscreen mode

TextDecoder handles the multi-byte grouping for you, which is exactly what the manual loop in trap 1 below fails to do.

One quirk worth knowing before you "clean" input in JS: parseInt does not throw, it stops at the first character it cannot parse. That behavior interacts badly with 0b prefixes:

parseInt("0b01001000", 2)   // 0  — the 0b prefix is not stripped here
Number("0b01001000")        // 72 — Number() does understand the prefix
Enter fullscreen mode Exit fullscreen mode

So a quick copy-paste cleanup with Number() looks tempting. It works, until a stray character slips in and you get NaN halfway through a 4 KB dump.

Method 3: when you just need the answer

For one-off dumps I stopped writing scripts entirely. Pasting the bits into a free online binary to text converter takes ten seconds, decodes both directions, and handles the copy-paste whitespace for me. Since it runs entirely in the browser, nothing gets uploaded, which matters when the dump comes from something half-proprietary. I still reach for the Python version when I need to batch-process thousands of lines, but for "what does this one line say", this browser-based tool wins.

Three traps that cost me an hour

Trap 1: treating every 8 bits as one character

My first attempt looped over 8-bit chunks and called chr() directly. It fell apart on anything non-ASCII:

>>> for c in ("11110000 10011111 10010001 10001011").split():
...     print(chr(int(c, 2)), end="")
...
👋>>>
Enter fullscreen mode Exit fullscreen mode

The wave emoji 👋 is four bytes (F0 9F 91 8B in UTF-8), not one. Bytes starting with 10 are continuation bytes and have no meaning alone. Any hand-rolled decoder has to respect UTF-8's lead-byte structure; bytes.decode("utf-8") and TextDecoder already do.

Trap 2: the codec that silently lies

Covered above, but it deserves its own heading because it burned me twice in one week. Latin-1 never raises an error, so bad decodes propagate far downstream. My rule now: if one accented character shows up as two odd ones, assume UTF-8 read as latin-1 or cp1252 and re-decode.

Trap 3: input that fails too quietly (or too loudly)

Dirty input comes in two flavors. Python at least fails loudly, which happened when I OCR'd a printed hex sheet and got the letter O mixed in:

ValueError: invalid literal for int() with base 2: '0100O100'
Enter fullscreen mode Exit fullscreen mode

Node fails silently. parseInt("0100O100", 2) returns 4 without complaint, and you only notice when the decoded string trails off mid-sentence. Whichever language you use, validate that the input is only 0 and 1 before parsing. When I suspect dirty input, I paste the first line into Utilvy's binary-to-text page as a sanity check — if it decodes cleanly there but my script doesn't, the bug is in my parsing, not the data.

Quick reference

Goal What I use Watch out for
Decode a short dump once this browser-based binary converter Paste may include line breaks; it tolerates them
Decode in a Python script bytes(int(c, 2) for c in chunks).decode("utf-8") Never decode with latin-1 by default
Decode in Node new TextDecoder("utf-8").decode(bytes) parseInt swallows bad digits; 0b prefix returns 0
Encode text to binary text.encode("utf-8"), format each byte %08b Non-ASCII means more than 8 bits per character

The pattern that saved me the most time: validate the bit string, parse bytes, then let a real UTF-8 decoder do the grouping. Everything else is shortcuts that break on the first multi-byte character.

More free browser-based utilities at utilvy.com.

Top comments (0)