TryBugHunt
rustType errorMedium

Five gigabyte file listed as 672 MB

BugFind the bug and fix the code

What it should do

file_size_mb(bytes) converts a file size in bytes to whole megabytes (1 MB = 1,048,576 bytes), rounded down. Example: file_size_mb(10485760) → 10

What happens instead

file_size_mb(5000000000) returns 672 instead of 4768.

fn file_size_mb(bytes: u64) -> u32 {
    bytes as u32 / 1_048_576
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the type errors pattern

Integer overflow, truncating casts with as, and types that do not convert the way you expect.

What you'll practise

A medium Rust debugging exercise about type errors: integer overflow, truncating casts with as, and types that do not convert the way you expect.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

What went wrong: as binds tighter than /, so bytes is cast to u32 before the division. A u32 holds at most about 4.29 billion. 5,000,000,000 does not fit, and as silently keeps only the low 32 bits, which is 705,032,704. Dividing that gives 672.

The fix: Divide while the value is still a u64, then cast the small result: (bytes / 1_048_576) as u32.

Remember: as never fails, it truncates. When narrowing a type, do the maths in the wide type first and cast last, and use parentheses to make the order clear.

The pattern behind it: type errors.

More type errors to practise

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/b0d03522-eabf-4df4-943f-2a77be95dc2a" title="Debugging challenge: Five gigabyte file listed as 672 MB" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/b0d03522-eabf-4df4-943f-2a77be95dc2a">TryBugHunt</a></p>