Computers think in binary, and programmers often read numbers in hexadecimal. PHP can convert between the common number systems.
| System | Digits | PHP to write it |
|---|---|---|
| Decimal (base 10) | 0 to 9 | 255 |
| Binary (base 2) | 0 and 1 | 0b11111111 |
| Octal (base 8) | 0 to 7 | 0377 or 0o377 |
| Hexadecimal (base 16) | 0 to 9 and a to f | 0xFF |
Converting from decimal
<?php
echo decbin(10) . "\n"; // binary
echo decoct(64) . "\n"; // octal
echo dechex(255); // hexadecimal
1010
100
ff
Converting to decimal
<?php
echo bindec("1010") . "\n";
echo octdec("100") . "\n";
echo hexdec("ff");
10
64
255
Between any bases
base_convert($number, $from, $to) works for bases 2 to 36. The number is passed as a string.
<?php
echo base_convert("ff", 16, 2) . "\n";
echo base_convert("z", 36, 10);
11111111
35
Where you meet these
- Colours:
#D95D39is three hex numbers, one each for red, green and blue. - File permissions:
chmod("file.txt", 0644)uses octal. - Bit flags: binary shows which options are on.
<?php
$hex = "D95D39";
[$r, $g, $b] = [hexdec(substr($hex, 0, 2)), hexdec(substr($hex, 2, 2)), hexdec(substr($hex, 4, 2))];
echo "rgb($r, $g, $b)";
rgb(217, 93, 57)
Leading zero means octal
012 is octal 10, not 12. Do not pad numbers with zeros in PHP source code. Write numbers as strings if you need the zeros.