All courses / Data Structures and Algorithms for Game Devs / Bits and bytes

Shifting bits

Challenge lesson, about 13 min, +20 XP

In the last lesson the flags were 1, 2, 4 and 8, typed by hand. That is fine for four effects. With twenty, you would need to type 524288 for bit 19 and get every digit right. The shift operators build those numbers for you, and they do a second job too: they slide a value into its own part of a bigger number, so you can pack several small values into one int and read each one back.

x << n moves every bit of x n places to the left. Zeros come in on the right. Every place to the left doubles a bit's value, so a shift by n multiplies by 2 to the power of n, as long as the result still fits.

Read the rest of this lesson and run the code in your browser.

Previous: Bit flags   Next: Negative numbers in binary

© 2026 Xero Media LLC. All rights reserved.