PHP Reference ยท Math Functions
PHP hexdec(), dechex(), octdec() and decoct() functions
Reference for PHP hexdec(), dechex(), octdec() and decoct(): convert between decimal, hexadecimal and octal, colours, file permissions and size limits.
These four functions convert between decimal numbers and hexadecimal (base 16) or octal (base 8) notation. dechex() and decoct() take an integer and return a string of digits; hexdec() and octdec() read such a string and return the number.
Hex shows up in colours (#ff8800) and byte values, octal in Unix file permissions (0755). Output is lowercase, with no 0x or leading zero. Input may be either case.
<?php echo dechex(255); // ff echo hexdec("ff"); // 255 echo decoct(493); // 755
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
dechex(int $num): string hexdec(string $hex_string): int|float decoct(int $num): string octdec(string $octal_string): int|float
| Name | Description |
|---|---|
$num |
An integer to convert. |
$hex_string |
A hexadecimal number as a string; upper and lower case digits both work. |
$octal_string |
An octal number as a string. |
Return value: dechex() and decoct() return lowercase digit strings without a prefix. hexdec() and octdec() return an int, or a float if the value exceeds PHP_INT_MAX.
Errors: none thrown. Characters that are not valid digits are skipped and a deprecation message is raised (PHP 7.4+).
Usage notes
- Negative numbers are printed as 64-bit two's complement:
dechex(-1)isffffffffffffffff. - Output has no prefix.
dechex(255)isff, not0xff. Input may carry the matching prefix (hexdec("0xff")is255), but other invalid characters are skipped with a deprecation notice. - Padding:
dechex(5)is5, not05. Usestr_pad()orsprintf("%02x", $n). - Octal literals such as
0755(or0o755since PHP 8.1) are written with a leading zero in code, but the functions deal with strings. - Large values become floats and lose precision. For exact big values use GMP, or
base_convert()with care. - File permissions:
chmod()needs the octal literal (0755), not a decimal or string.chmod("file", "755")is wrong, since the string converts to decimal 755. - Binary data: to turn a whole binary string into hex use
bin2hex()andhex2bin()instead.