Skip to content

PHP Tutorial Numbers and Math

Number Systems and Base Conversion

Lesson 79 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Computers think in binary, and programmers often read numbers in hexadecimal. PHP can convert between the common number systems.

SystemDigitsPHP to write it
Decimal (base 10)0 to 9255
Binary (base 2)0 and 10b11111111
Octal (base 8)0 to 70377 or 0o377
Hexadecimal (base 16)0 to 9 and a to f0xFF

Converting from decimal

index.php
PHP
<?php
echo decbin(10) . "\n";    // binary
echo decoct(64) . "\n";    // octal
echo dechex(255);          // hexadecimal
Output
OUTPUT
1010
100
ff

Converting to decimal

index.php
PHP
<?php
echo bindec("1010") . "\n";
echo octdec("100") . "\n";
echo hexdec("ff");
Output
OUTPUT
10
64
255

Between any bases

base_convert($number, $from, $to) works for bases 2 to 36. The number is passed as a string.

index.php
PHP
<?php
echo base_convert("ff", 16, 2) . "\n";
echo base_convert("z", 36, 10);
Output
OUTPUT
11111111
35

Where you meet these

  • Colours: #D95D39 is 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.
index.php
PHP
<?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)";
Output
OUTPUT
rgb(217, 93, 57)
dangerous
Leading zero means octal
In code, 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.