CodeGym /행동 /Kotlin SELF /Encoding: why “garbled text” appears

Encoding: why “garbled text” appears

Kotlin SELF
레벨 44, 레슨 0
사용 가능

1. Introduction

If you’ve ever opened a file in a basic editor and thought, “well, it’s text, it has letters,” you’re in good company: almost everyone thinks that until their first real encounter 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) in a very long sequence. And “letters” appear later—when some program takes those bytes and decides how to turn them into characters.

Imagine bytes as musical notes written as digits, and an encoding as the rule “which digit corresponds to which note” (and sometimes how many digits are needed per note). If you play the music while interpreting the digits with the wrong table, it will sound, at best, strange. Text works the same way: the bytes are the same, but the interpretation rules differ—and instead of “Hello” you might see “Привет” or “??????”.

It’s very important to fix the boundary:

Level What it is How it’s represented in Kotlin
File on disk A sequence of bytes
ByteArray
Text in a program A 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—there is only ByteArray.

2. Encoding: the rule “bytes ↔ text”

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

It’s useful to think of an encoding as “glasses.” Bytes are the same object in 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, but as a meaningless set of symbols. And that’s exactly why “garbled text” 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. We will most often use ready-made values from Charsets, for example Charsets.UTF_8. Today we won’t dive into what encodings exist and how they differ—we just need the principle: the encoding must be consistent between writing and reading.

To feel the idea with your hands, let’s start simple: string → bytes.

fun main() {
    val text = "안녕하세요"
    val bytes = text.toByteArray(Charsets.UTF_8)
    println(bytes.size) // 15 (in UTF-8, Hangul typically takes more than 1 byte)
}

Here we’ve already taken 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 fix the terminology at a practical level. When you have a ByteArray and you want a String, you do decoding. When you have a String and you want to write bytes to a file, you do 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 conveyor. The diagram below explains about 80% of mysteries around “why the text broke.”

flowchart TD
    A[String: '안녕하세요'] -->|"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: '안녕하세요']

In Kotlin, both operations look quite 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 encodings match—everything is fine. “Garbled text” appears when the encodings don’t match.

4. Diagnostics and “garbled text” in real code

How to “see the bytes” so you stop guessing

At the beginning of learning encodings, a typical situation happens: “I opened a file, I see nonsense, I tried another encoding—I see different nonsense.” This quickly turns into shamanism. To avoid guessing, it helps to be able to print bytes in a clear form, for example hex (hexadecimal). This is not magic and not “for hackers,” just a convenient way to see what’s actually stored in the file.

Let’s add a small utility to our learning 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 really contains bytes 48 65 6C 6C 6F.” That’s not emotions—that’s facts.

By the way, the same bytes can be decoded immediately as UTF-8 (or ASCII—for English text, that will coincide):

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

    println(text) // Hello
}

How “garbled text” appears

Now—the central focus of the lecture. “Garbled text” is almost always the situation “the bytes are correct, but we read them with the wrong rules.” That is, the problem is not that “the file got corrupted,” but that we decoded incorrectly (or earlier wrote using the wrong encoding). The simplest way to see it is to encode text one way and decode it another way.

Let’s take a word, encode it in UTF-8, and then try to read those bytes as ASCII. ASCII is very limited (basically Latin letters and control symbols), so everything that doesn’t fit will be turned into “replacement characters” (often ?).

fun main() {
    val original = "안녕하세요"
    val bytes = original.toByteArray(Charsets.UTF_8)

    val wrong = String(bytes, Charsets.US_ASCII)
    println(wrong) // ?????  (often like this; depends on replacement)
}

Important: the bytes did not change. The interpretation rule changed. Therefore the output “?????” is not a “broken file,” but a logical result of “ASCII can’t represent Hangul.”

You can do another illustrative trick: for the word "Hello", the bytes in ASCII and UTF-8 are the same. That’s exactly 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 "안녕하세요" there will be no such coincidence, and that’s normal.

Example: “BudgetBuddy” and the I/O boundary

Now we’ll take a small but very practical step toward an “adult” 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” in order to debug cases where the file came from a different system or editor.

The idea is simple: we’ll make a function that reads a file as bytes and turns it into a string via explicit decoding. Today we’ll fix only the principle itself (decode explicitly)—the choice of a specific encoding and the discipline of “don’t rely on the system default” we’ll expand 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, it looks a bit “longer” than readText(). But now we have a point where we can:

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

For example, if we suspect the file is being read “wrong,” we can print 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 are not “fixing” anything here. We’re doing what programmers do best—stop guessing and start measuring.

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

This section is needed to remove a common illusion. A student often says: “But I opened the file in the editor and it’s fine there. Why does the program see garbled text?” This is an excellent question because it highlights the key idea: the editor also chooses an encoding. Sometimes automatically, sometimes based on project settings, sometimes by “guessing.” So you see it “fine” not because the file is “magically correct,” but because the editor guessed right or you configured it correctly.

The program, however, decodes exactly as you told it (or as it ended up “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 that 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: assuming that a String “lies in the file” as a String.
This is one of the most persistent thinking errors. In Kotlin, String is an object in program memory. In a file—only bytes. If you keep this in mind, you will automatically look for the issue at the “bytes ↔ text” boundary, instead of trying to fix “wrong characters” with strange replace().

Mistake №2: trying to “fix garbled text” 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 “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 (for example, Hangul) the size in bytes can be larger. If you start slicing text “by bytes” while expecting “by characters,” you can easily break data.

Mistake №4: debugging “by eye” without printing 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 the numbers. Simple diagnostics via the hex representation of the first bytes often saves hours.

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

1
과제
Kotlin SELF, 레벨 44, 레슨 0
잠금
메시지의 무게
메시지의 무게
1
과제
Kotlin SELF, 레벨 44, 레슨 0
잠금
전보 디코더
전보 디코더
1
과제
Kotlin SELF, 레벨 44, 레슨 0
잠금
헥스 명함
헥스 명함
1
과제
Kotlin SELF, 레벨 44, 레슨 0
잠금
고장난 번역기
고장난 번역기
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION