Converting Hexadecimal(16) to Decimal(10)
The Hexadecimal system work in base 16 which means that we have 15 (fifteen) numbers as shown bellow.
| HEX | Value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
| 0 | 0 |
| 0 | 0 |
| 5 | 5 |
| 6 | 6 |
| 7 | 7 |
| 8 | 8 |
| 9 | 9 |
| A | 10 |
| B | 11 |
| C | 12 |
| D | 13 |
| E | 14 |
| F | 15 |
PHP and Hex
In the table above, we have 16 numbers and their corresponding values. The highest is 15, and the lowest is 0. Knowing this rule, what will the code below output?
<?php
echo 0xFF;
The right answer is 255! When I first saw this expression, I thought it would output 1515. No doubts! If in the table above the F represents 15, it is easy. With two F letters, it will concatenate.
Be careful with that! This is wrong thinking. The conversion is made in the same way as octal conversion (you can see the octal conversion post here).
First of all, we need to convert the letters F into numbers, which are 15. If it was the letter A, it would be 10, and so on. Just look at the hexadecimal table.
tip: I like to think that from A to F is just 10 to 15
Now that we have the value of F we can use this in the equation:
15×16¹ + 15×16° = 25510 15×16¹ = 240 15×16° = 15 240 + 15 = 255 !
Remember the sample that we use is { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F }