Hexadecimal and Octal


There is another numbering system which programmers are very fond of. This is the hexadecimal (base-16) system. Each column of a hexadecimal number represents a value of 16 raised to a given power. The rightmost column (as with all systems) contains only units. The next column is "16s".  The next column is "256s" (16 raised to the power 2) and the next column is "4096s" (16 raised to the power 3). The difficulty arises from the fact that a base-16 system uses digits with a value between 0 and 15 (inclusive). However, each column can only hold a single digit (as with any other numbering system). Therefore we can't, for example, have the figure 15 in the rightmost column to represent 15 units. This is because if we wrote 15, this would actually represent 5 units and 1 x 16! To circumvent this problem, the values 10 through 15 are assigned letters, namely A to F.

160 = 1
161 = 16
162 = 256
163 = 4096
164 = 65536
165 = 1048576

This is better explained with an example. Consider the number B5FH. The H on the end is simply a convention to identify the number is a hexadecimal number. The above figure is decomposed (starting with the rightmost figure) as follows:

(15 x 1) + (5 x 16) + (11 x 256) = 2911

Why would we want to use such an awkward system? Well, it turns out that hexadecimal is a useful shorthand for representing much longer binary numbers.  This is because any binary nybble (4 bits) can be represented with a single hexadecimal digit. How does this work?  Well, 24 = 161 = 16. Similarly, 28 = 162 = 256. Hence an 8 bit binary number is easily represented using just 2 hexadecimal figures.

How about another example... 

10111010B = 186 (decimal)

If we break this binary number into two nybbles, we get 1011 and 1010. The first nybble is 11 in decimal which is B in hex. The second nybble is 10 in decimal which is A in hex. Amazingly, when you combine these two hex values to give BAH, you find this equals 186 in decimal:

(10 x 1) + (11 x 16).

It's magic...

In conclusion, hexadecimal is useful for representing long binary numbers by splitting the binary number into 4 bit nybbles (starting from the right).


Another system you may come across is the octal system. While not as common as hexadecimal, octal still proves useful to programmers as a shorthand for representing binary digits.

Octal is base-8, and therefore a single octal digit can hold any value from 0 to 7. Since 8 is also 2 raised to the power of 3, it turns out that any single octal digit can be used to represent 3 binary digits (in the same way that a single hex digit can represent any 4 bits).

If you work with computers long enough, it is inevitable that you run into hex. Conversely, you may never run into octal! But I've included it here just in case you do!

What's next

The next section looks at some more advanced concepts in binary: how to represent negative values and how to perform binary arithmetic.