Skip to main content

The Cast That Dropped Four Bytes

This video presents the same text shown beside it, spoken and on screen. It adds nothing the text does not say.

State

Truncation from a type cast follows exact arithmetic — the retained bytes keep the value's remainder within the smaller type's range — and one trace shows a large number becoming a small wrong one silently.

Show

Recall video 0196: a four-byte integer tops out near two billion. Take a running total that has outgrown it inside an eight-byte type — say the value 2 to the 32nd power, plus 7. Cast it down into four bytes. The mechanism from video 0366 executes: four bytes drop. What remains is the value's remainder after dividing by 2 to the 32nd — the multiple of 2 to the 32nd vanishes entirely, and the stored result is 7. Not roughly seven. Exactly 7, from a number more than four billion large. No error was thrown, because video 0370's machinery had nothing to catch: the cast was legal, signed for in the source. A ledger showing 7 where billions belonged is the whole lesson in one cell — the arithmetic of dropped bytes is deterministic, so the bug is deterministic, and so is the prevention: know the ranges before signing the cast.

Watch for

The silence is the hazard — truncation announces nothing, and the wrong value is a well-formed value.