PHP base_convert() Function
The PHP base_convert() function converts a number between specified bases. It returns a string containing number represented in base to_base. The base in which number is given is specified in from_base. Both from_base and to_base have to be between 2 and 36, inclusive. Digits in numbers with a base higher than 10 will be represented with the letters a-z, with a representing 10, b representing 11 and z representing 35. The case of the letters does not matter.
Note: The base_convert() may lose precision on large numbers due to properties related to the internal "double" or "float" type used.
Syntax
base_convert(number, from_base, to_base)
Parameters
number |
Required. Specify the number to convert. |
from_base |
Required. Specify the base number is in |
to_base |
Required. Specify the base to convert number to |
Return Value
Returns the number converted to base to_base.
Example:
In the example below, base_convert() function is used to convert a given number from one base to another.
<?php //converting from decimal to binary echo "base_convert(0, 10, 2) = " .base_convert(0, 10, 2)."\n"; echo "base_convert(10, 10, 2) = " .base_convert(10, 10, 2)."\n"; //converting from hexadecimal to binary echo "base_convert('ff', 16, 2) = " .base_convert('ff', 16, 2)."\n"; echo "base_convert('1f', 16, 2) = " .base_convert('1f', 16, 2)."\n"; //converting from hexadecimal to octal echo "base_convert('fff', 16, 8) = " .base_convert('fff', 16, 8)."\n"; echo "base_convert('1ff', 16, 8) = " .base_convert('1ff', 16, 8)."\n"; ?>
The output of the above code will be:
base_convert(0, 10, 2) = 0 base_convert(10, 10, 2) = 1010 base_convert('ff', 16, 2) = 11111111 base_convert('1f', 16, 2) = 11111 base_convert('fff', 16, 8) = 7777 base_convert('1ff', 16, 8) = 777
❮ PHP Math Reference