AlgoViz

Number bases (binary & hex)

easy 14 min

Every number base works the same way: each digit is multiplied by the base raised to the power of its position.

Remember it

The few things worth knowing cold, and how to make them stick.

Memory hook

Digit times base to the power of its place, then add: that one rule reads every base.

A car odometer. In decimal each wheel has ten symbols and rolls the wheel to its left after 9. A binary odometer has wheels with only 0 and 1, so it rolls over after every 1; a hex odometer has sixteen symbols and only rolls after F. The counting is the same, only the size of the wheel changes.

Cheat sheet

Value
sum of digit times base^position
Powers of 2
1 2 4 8 16 32 64 128 256 512 1024
Hex letters
A=10 B=11 C=12 D=13 E=14 F=15
1 hex digit
4 bits (a nibble)
1 byte
8 bits, 0 to 255, 00 to FF
42
101010 = 0x2A
Bits for n
floor(log2 n) + 1
Decimal to base b
n % b, n // b, reverse
Python
int(s, b), bin, hex, format(n, '08b')

Spot it when you see

  • A 0x prefix, a # colour code or a memory address: think hex.
  • Flags, masks, permissions, or counting and flipping bits: think binary.
  • Problems named number of 1 bits, reverse bits, power of two or single number.
  • Converting a number to a string in another base, or adding numbers given as digit strings.
  • Byte limits like 255, 256, 127 or 65,535 in the constraints.

Tricks that stick

  • Double from 1, or halve to 1: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024.
  • Hex letters are their position in the alphabet plus 9: A is 1 + 9 = 10, F is 6 + 9 = 15.
  • All ones is one less than the next power of two: 1111 = 15, 11111111 = 255.
  • A single 1 followed by zeros is a power of two: 1000 = 8, 10000000 = 128.
  • Remainders come out backwards: the first one you get is the last digit you write.
  • Hex to binary: four bits per digit, no decimal detour. 2A is 0010 1010.

Do not forget

  • Reading division remainders top-down, which reverses the digits.
  • Forgetting that bin and hex return strings with 0b and 0x in front.
  • Calling int on a hex string without passing base 16.
  • Dropping leading zeros when a fixed width of 4 or 8 bits matters.
  • Returning an empty string for 0 from a hand-written converter.
  • Expecting bin of a negative number to show two's complement; Python shows a minus sign.