CodeGym /Courses /Kotlin SELF /Encoding: why “mojibake” appears

Encoding: why “mojibake” appears

Kotlin SELF
Level 44, Lesson 0
Available

1. Introduction

If you’ve ever opened a file in Notepad and thought, “well it’s text, there are letters,” you’re in good company: almost everyone thinks that until their first collision with encodings. In reality, the operating system and the file system don’t store “letters,” “strings,” or “paragraphs.” They store numbers from 0 to 255 (bytes), just in a very long sequence. And “letters” appear later—when some program takes those bytes and decides how to turn them into characters.

Imagine that bytes are musical notes written as digits, and an encoding is the rule “which digit corresponds to which note” (and sometimes—how many digits are needed for one note). If you play the music while interpreting the digits with the wrong table, the result will be strange at best. With text it’s the same: the bytes are the same, but the interpretation rules are different—and instead of the intended text you see “Привет” or “??????”.

It’s very important to pin down the boundary:

Level What it is How it’s represented in Kotlin
File on disk Sequence of bytes
ByteArray
Text in the program Sequence of characters
String
Conversion rule How bytes turn into characters and back “encoding” (Charset)

In Kotlin (on the JVM) we can “honestly” see a file’s bytes like this:

import java.io.File

fun main() {
    val bytes = File("data/note.txt").readBytes()
    println(bytes.size) // for example: 128
}

So far there is no text—only ByteArray.

2. Encoding: the “bytes ↔ text” rule

In this section we’ll carefully introduce a new term, because without it it will be hard to talk about what comes next. An encoding is not a “file format” and not a “language,” but a conversion rule between bytes and characters. And it’s a two-way rule: how to turn bytes into text (decoding) and how to turn text into bytes (encoding). In other words, the encoding is part of the contract: “I wrote the bytes like this; you read them like this.”

It’s useful to think of an encoding as “glasses.” The bytes are the same piece of reality. The encoding is the lens. Put on the right glasses—you see normal text. Put on the wrong ones—you see the same bytes as a meaningless set of characters. That’s exactly why “mojibake” often looks stable: it’s not random noise, but a very specific interpretation.

At the API level in Kotlin/JVM, an encoding is represented by the Charset type. Most often we’ll use predefined values from Charsets, for example Charsets.UTF_8. Today we won’t dive into which encodings exist and how they differ—we just need the principle: the encoding must match between writing and reading.

To get a hands-on feel, let’s start simple: string → bytes.

fun main() {
    val text = "Hello"
    val bytes = text.toByteArray(Charsets.UTF_8)
    println(bytes.size) // 5 (for plain ASCII text, UTF-8 uses 1 byte per character)
}

Here we already made an important step: we explicitly said “turn the string into bytes using UTF-8.”

3. Encoding and decoding: two directions of the same path

It’s easy to get confused by the words, so let’s lock down the terminology in everyday terms. When you have a ByteArray and you want a String, you are doing decoding. When you have a String and you want to write bytes to a file, you are doing encoding. These are mirror operations, and they must use the same encoding if you want to get the original text back.

It’s very convenient to keep this in mind as a small pipeline. The diagram below explains about 80% of mysteries like “why did the text break?”

flowchart TD
    A[String: 'Hello'] -->|"encode: toByteArray(UTF-8)"| B[ByteArray]
    B -->|write to file| C[(File on disk)]
    C -->|"readBytes()"| D[ByteArray]
    D -->|"decode: String(bytes, UTF-8)"| E[String: 'Hello']

In Kotlin both operations look fairly straightforward:

  • Encoding: text.toByteArray(charset)
  • Decoding: String(bytes, charset)

Mini example “there and back”:

fun main() {
    val original = "Hello"
    val bytes = original.toByteArray(Charsets.UTF_8)
    val decoded = String(bytes, Charsets.UTF_8)

    println(decoded) // Hello
}

As long as the encoding matches—everything is fine. “Mojibake” appears when the encodings don’t match.

4. Diagnostics and “mojibake” in real code

How to “see the bytes” so you stop guessing

When first learning about encodings, a typical situation happens: “I opened the file, I see garbage, I tried another encoding—I see different garbage.” This quickly turns into shamanism. To stop guessing, it’s useful to be able to print bytes in a readable form, for example hex (hexadecimal). This isn’t magic and it isn’t “for hackers”—it’s just a convenient way to see what is actually stored in the file.

Let’s add a small utility to our study project: convert a ByteArray into a string of hex values. Here we use simple formatting and joinToString().

fun toHex(bytes: ByteArray): String {
    return bytes.joinToString(" ") { b -> "%02X".format(b) }
}

fun main() {
    val bytes = byteArrayOf(72, 101, 108, 108, 111)
    println(toHex(bytes)) // 48 65 6C 6C 6F
}

Now we can diagnose: “the file actually contains bytes 48 65 6C 6C 6F.” That’s no longer emotions—it’s facts.

By the way, the same bytes can be decoded right away as UTF-8 (or ASCII—for English text it will match):

fun main() {
    val bytes = byteArrayOf(72, 101, 108, 108, 111)
    val text = String(bytes, Charsets.UTF_8)

    println(text) // Hello
}

How “mojibake” appears

Now—the central point of the lecture. “Mojibake” is almost always the situation “the bytes are correct, but we’re reading them using the wrong rules.” That is, the mistake isn’t that “the file got corrupted,” but that we performed the wrong decoding (or earlier wrote with the wrong encoding). The simplest way to see this is to encode text one way and decode it another way.

Take some non-ASCII text, encode it as UTF-8, and then try to read those bytes as ASCII. ASCII is very limited (basically Latin letters and control symbols), so anything that doesn’t fit will be turned into “replacement” characters (often ?).

fun main() {
    val original = "Hello"
    val bytes = original.toByteArray(Charsets.UTF_8)

    val wrong = String(bytes, Charsets.US_ASCII)
    println(wrong) // Hello  (ASCII and UTF-8 coincide for plain English text)
}

Important: the bytes did not change. The interpretation rule changed. When you see “??????”, that’s not a “broken file,” but a logical outcome of “this charset can’t represent those characters.”

You can do one more illustrative trick: for the word "Hello", ASCII and UTF-8 produce identical bytes. That’s why it sometimes feels like “encoding doesn’t matter”: for English text many encodings “accidentally work.”

fun main() {
    val s = "Hello"
    val a = s.toByteArray(Charsets.US_ASCII)
    val u = s.toByteArray(Charsets.UTF_8)

    println(a.contentEquals(u)) // true
}

But for non-ASCII text this coincidence won’t happen, and that’s normal.

Example: “BudgetBuddy” and the I/O boundary

Now let’s take a small but very practical step toward a “grown-up” application. Imagine we have a console project BudgetBuddy (expense tracking) that stores data in a text file "data/expenses.txt". We already know how to read text via readText(), but today we want to understand what happens at the boundary “file → string,” so we can debug cases where the file came from a different system or editor.

The idea is simple: make a function that reads a file as bytes and turns it into a string with explicit decoding. Today we’ll only lock in the principle itself (explicit decoding)—the choice of a specific encoding and the discipline of “don’t rely on the system default” will be expanded in the next lectures of the day.

import java.io.File

fun readTextUtf8(file: File): String {
    val bytes = file.readBytes()
    return String(bytes, Charsets.UTF_8)
}

fun main() {
    val text = readTextUtf8(File("data/expenses.txt"))
    println(text.length) // for example: 57
}

Yes, this looks a bit “longer” than readText(). But now we have a point where we can:

  • print the first bytes,
  • make sure the file is actually not empty,
  • verify that we’re decoding using exactly the rule we expect.

For example, if we suspect the file is being read “crookedly,” we can output the first few bytes:

import java.io.File

fun main() {
    val bytes = File("data/expenses.txt").readBytes()
    val preview = bytes.take(12).toByteArray()

    println(toHex(preview)) // for example: 50 61 79 6D 65 6E 74 3A 20 ...
}

Notice: we’re not “fixing” anything here. We’re doing what programmers do best—we stop guessing and start measuring.

Why “it looks fine in the editor” is not a guarantee

This section is here to remove a popular illusion. A student often says: “But I opened the file in an editor, and it looks fine. Why does the program see mojibake?” This is an excellent question because it highlights the key idea: the editor also chooses an encoding. Sometimes automatically, sometimes via project settings, sometimes by “guessing.” So you see it “fine” not because the file is “magically correct,” but because the editor guessed correctly or you configured it correctly.

A program, however, decodes according to what you told it (or whatever happens “by default”). Therefore, the situation “the editor shows it fine, but the program doesn’t” means: the editor and the program chose different decoding rules. And this brings us back to the main thesis of the lecture: text is bytes + rules.

Once you accept this model, many oddities stop being odd. You stop thinking “the file is cursed” and start thinking “which charset was used when writing and which when reading.” And that’s a problem that has a solution.

5. Typical mistakes

Mistake #1: thinking that a String “sits in the file” literally as a String.
This is one of the most persistent mental traps. In Kotlin, String is an object in the program’s memory. In a file—only bytes. If you keep this in mind, you’ll automatically look for the problem at the “bytes ↔ text” boundary instead of trying to fix “wrong characters” with weird replace().

Mistake #2: trying to “fix mojibake” by replacing characters instead of decoding correctly.
Sometimes you want to do something like text.replace("Ð", "P"). This is almost always a path to even more chaos: you’re treating the symptom, not the cause. The correct repair point is choosing the correct charset during decoding.

Mistake #3: thinking that “1 character = 1 byte.”
This is a common trap after the first lessons with ByteArray. For ASCII it often “looks like” that, but for Unicode text the byte size can be larger. If you start slicing text “by bytes” expecting “by characters,” it’s easy to corrupt data.

Mistake #4: debugging “by eye” without printing the bytes.
When your problem is at the byte level, looking only at println(text) is like trying to understand a bug in arithmetic without printing numbers. Simple diagnostics via a hex view of the first bytes often saves hours.

Mistake #5: mixing layers: reading a file, parsing, and validating in one place.
When everything is done in one big chunk of code, you don’t know where exactly things went wrong: the file didn’t read, the bytes are wrong, the decoding is wrong, or the parser complains. It’s better to have a separate step “get bytes,” a separate step “decode into a string,” and only then—business logic.

1
Task
Kotlin SELF, level 44, lesson 0
Locked
Message weight
Message weight
1
Task
Kotlin SELF, level 44, lesson 0
Locked
Telegraph Decoder
Telegraph Decoder
1
Task
Kotlin SELF, level 44, lesson 0
Locked
Hex business card
Hex business card
1
Task
Kotlin SELF, level 44, lesson 0
Locked
Broken translator
Broken translator
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION