Binary & Hex

Every value in your game — health, coins, a sprite's color, the position of a turret — is a stack of bits in memory. This is the reference for reading them: base 2, base 16, the ranges the exam asks about, and the overflow you can trigger in your own game with one line of code.

Why base 2 exists

Hardware holds only two reliable voltage states — high and low, on and off, 1 and 0. Everything the machine does must be expressible as answers to yes/no questions, so every number, every letter, every frame of your game is bits. You write 5; the machine reads 101.

Reading binary

Each place is worth twice the place to its right — powers of two. To read a binary number, add the values where a 1 sits:

Place2³ = 82² = 42¹ = 22⁰ = 1Total
10111 → 801 → 21 → 111
011001 → 41 → 206
11111 → 81 → 41 → 21 → 115

Two facts the exam builds questions on: all ones is always one less than the next power of two (1111 = 16 − 1), and n bits count 0 through 2ⁿ − 1. Four bits: 0–15. Eight bits (a byte): 0–255. Thirty-two bits (a C# int): up to 2,147,483,647 — a number you have seen in 9.1's overflow demo.

Converting, by hand

Hexadecimal — binary with better handwriting

One hex digit covers exactly four bits, so a byte is always two hex digits and 8 bits never needs 8 written characters. 0xFF = 255. 0x10 = 16 (yes, sixteen — it is one sixteen and zero ones, not ten).

Dec0123456789101112131415
Hex0123456789ABCDEF
Bin0000000100100011010001010110011110001001101010111100110111101111

Where you touch hex this year: sprite colors — Unity's Color32 is four bytes (R, G, B, alpha), and the site's theme blue #6cb2ff is (108, 178, 255) in decimal. Where the web touches hex: every CSS color. The details are in 9.2.

Overflow — the bug you can build in one line

Debug.Log(int.MaxValue + 1);   // prints -2147483648

Add 1 to the largest 32-bit signed int and the sum cannot fit, so the bit pattern wraps around to the most negative number — the sign bit itself. The exam loves this as "rounding" for integers; the same idea in binary arithmetic is called overflow. Your game will not hit it with honest play (2.1 billion coins!), but any code that adds without checking can, and a cheat engine can make your coins negative in a heartbeat. Guard clauses are not just about nulls — they are about ranges.

Floats are bits too — and they lie

Debug.Log(0.1f + 0.2f == 0.3f);   // False!

A float stores numbers in binary scientific notation (sign, exponent, fraction bits), and 0.1 has no exact binary representation — the same way 1/3 has no exact decimal one. The comparison is close but not equal. That is why game code compares floats with tolerances, or uses ints for anything that must count exactly (coins are int for this reason — 5.1's right-size-the-data argument, now with bit-level proof).

The exam-question shapes

Where you meet bits this year

← Unit 9 All docs The Internet →