This week the CS50x course I am working through is teaching (more accurately getting me to learn about) pointers in C, and using images to help understand the concept. I've been looking through bitmap files and getting to grips with how computers make images, something I've always been curious about. Three weeks ago I also looked at binary and how computers use only 1's and 0's to get stuff done. I thought I'd got to grips with it, but looking at hexadecimal, which is used for images, really cemented this understanding.
What is hexadecimal?
Instead of going up to 10 in each digit you go up to 16.
In decimal we count, 0, 1, 2, ... 8, 9 and then we have to add another digit to get to 10 (two digits). Whereas in hexadecimal when we get past nine we use the letters a to f (which take up one digit (or bit in a computers perspective)). See this table for a clearer picture of this:
Decimal | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
Hexadecimal | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
This means we can write bigger numbers in a shorter number of bits (digits).
F
in hexadecimal would equal to 15. But what would FF
equal to? Can you work it out?
In decimal the first digit of 35 is 3, but we know it represents 30 (3 * 10). 10 here is the base (decimal). We then add the next digit to the first (30 + 5 = 35).
In hexadecimal the first digit of FF
is 15, but it actually represents 240 (15 * 16). 16 here is the base (hexadecimal). We then add the next digit to the first (240 + F
= 255). Remember F = 15.
Let's clarify this a little with one more example using a table. The number is 345. Here it is in decimal (base 10):
Decimal number: | 3 | 4 | 5 | |
Base to the power of each digit: | 10^2 | 10^1 | 10^0 | |
Which equals: | 100 | 10 | 1 | |
Total: | 300 + | 40 + | 5 | = 345 |
Whereas if we had 345 in hexadecimal (base 16) it would look like this:
Hexadecimal number: | 3 | 4 | 5 | |
Base to the power of each digit: | 16^2 | 16^1 | 16^0 | |
Which equals: | 256 | 16 | 1 | |
Total: | 768 + | 64 + | 5 | = 837 |
See if you can work out the hexadecimal versions of these decimal numbers: 11, 78, 613. Use the tables to help.
I hope this has helped spread at least a little light on the hexadecimal! In my next post I'll let you know why this is so helpful in computers, and why this has helped me with binary.