# Decimal, binary, hexadecimal

In our lives we normally use the decimal system (with digits from 0 to 9), but computers don't work that way. When we're programming, we also tend to use other numeric systems, such as binary (only digits 0 and 1) and hexadecimal (with sixteen digits).

## Decimal

Let's start with the one we're all familiar: decimal. Explaining this one first so you can get the gist of the rest. When we write numbers, we use ten digits:

`0 1 2 3 4 5 6 7 8 9`

When we need to express larger numbers, we add an extra digit to the left, then another one, and so on. So it goes 0, 1, … 8, 9, 10, 11 … 99, 100, 101 … 999, 1000, 1001… you get the idea (I hope).

The important part here to understand is that each digit in a number represents a multiple of a power of 10, hence we call decimal to be "base 10":

123 = 1×10^{2} + 2×10^{1} + 3×10^{0}

Or in other words:

123 = 1×100 + 2×10 + 3×1

## Binary

Computers are different beasts and don't work in decimal. Instead, their
components can only hold two states ("on"/"off"). In order to express
numbers, they use the *binary* system, which only has two digits:

`0 1`

As you can imagine, digits are stacked the same way as with decimal: 0, 1, 10, 11, 100, 101, 110, 111, 1000, 1001, etc. As there are only two digits available, numbers are expressed in powers of two instead (so binary is "base 2"):

1010 (bin) = 1×2^{3} + 0×2^{2} +
1×2^{1} + 0×2^{0}

Or without using exponents:

1010 (bin) = 1×8 + 0×4 + 1×2 + 0×1

## Hexadecimal

Working with binary is cumbersome, numbers become huge and hard to read
quickly. Instead, what we normally do is use *hexadecimal* (often
shortened to "hex"), which has 16 digits, where letters A to F represent
values from ten to fifteen:

`0 1 2 3 4 5 6 7 8 9 A B C D E F`

Again, same rules as usual apply, this time with powers of 16:

5E6A (hex) = 5×16^{3} + 14×16^{2} +
6×16^{1} + 10×16^{0}

Or again:

5E6A (hex) = 5×4096 + 14×256 + 6×16 + 10×1

The important part here is that 1 hexadecimal digit is exactly 4 bits:

- 0 = 0000
- 1 = 0001
- 2 = 0010
- 3 = 0011
- 4 = 0100
- 5 = 0101
- 6 = 0110
- 7 = 0111
- 8 = 1000
- 9 = 1001
- A = 1010
- B = 1011
- C = 1100
- D = 1101
- E = 1110
- F = 1111

As such, converting between hexadecimal and binary is extremely easy once you learn the above list, and in practice we're going to use the former much more often. For example, hexadecimal 1A0 in binary is 0001 1010 0000 i.e. 110100000. Which one is easier to read?

#### Iwis says

In most programming languages, hexadecimal numbers are prefixed with
`0x`

(e.g. `0x1A0`

). In 68000 assembly,
hexadecimal numbers are prefixed with `$`

(e.g. `$1A0`

).