PHP Reference ยท Math Functions
PHP base_convert(), bindec() and decbin() functions
Reference for PHP base_convert(), bindec() and decbin(): convert numbers between bases 2 to 36, binary strings, negative numbers and precision limits.
base_convert() converts a number written as a string from one base to another, with bases from 2 to 36. Digits above 9 use the letters a to z, in either case on input and in lowercase on output. bindec() reads a binary string into a number, and decbin() writes an integer in binary.
Numbers travel as strings because a number in base 2 or 36 is just text. The functions work through PHP's native int and switch to float for values beyond PHP_INT_MAX, so they lose exactness on very large values; use GMP for those.
<?php echo base_convert("ff", 16, 2); // 11111111 echo bindec("1010"); // 10 echo decbin(10); // 1010
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
base_convert(string $num, int $from_base, int $to_base): string bindec(string $binary_string): int|float decbin(int $num): string
| Name | Description |
|---|---|
$num |
The number to convert, as a string of digits valid in $from_base. |
$from_base |
The base of $num, from 2 to 36. |
$to_base |
The base to convert to, from 2 to 36. |
$binary_string |
A string of 0 and 1 characters. |
Return value: base_convert() returns a lowercase string. bindec() returns an int, or a float when the value does not fit into an integer. decbin() returns a string of binary digits.
Errors: base_convert() throws a ValueError if a base is outside 2 to 36. Characters that are invalid for the source base are skipped and a deprecation message is raised (PHP 7.4+).
Usage notes
- Input is a string, so write large values as strings. A leading
0x,0bor0oprefix that matches the source base is accepted and skipped (bindec("0b101")is5). - Precision:
base_convert()andbindec()use floats abovePHP_INT_MAX, so the last digits can be wrong. For exact large conversions usegmp_strval(gmp_init($n, $from), $to). - Negative numbers:
decbin(-1)is 64 ones becausedecbin()shows the two's complement of the integer. There is no sign handling inbindec()either. - Leading zeros are not kept:
decbin(5)is101. Pad withstr_pad()orsprintf("%08b", $n). sprintf()is often easier:%b,%o,%xand%Xformat integers in binary, octal and hex.- Literals: in code you can write
0b1010,0o17,0x1fdirectly, without calling a function. - Hex and octal helpers:
hexdec(),dechex(),octdec()anddecoct()cover bases 16 and 8.