Skip to main content
SWStudyWalks Search

Computer Science / Unit 7   CS 0371 worked example, 60 to 90 seconds

The Cast That Dropped Four Bytes

Captions available

The idea

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.

In practice

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.

Where people slip

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

Your place on the trail

Every lesson rests on earlier ones and opens later ones. Tap any to jump.

Something wrong in this lesson? Flag it  ·  Sources for Computer Science