PHP base_convert() Function
Definition
We can use base_convert() to convert binary directly to hexadecimal, or octal to duodecimal (base 12) or hexadecimal to vigesimal (base 20).
Syntax
PHP base_convert() function's format is as follows.
string base_convert ( string num, int from_base , int to_base )
Parameter
base_convert()
takes three parameters:
a number to convert,
the base to convert from, and
the base to convert to.
Return
The return value is the number converted to the specified base. The return type is String.
Example 1
For example, the following two lines are identical:
<?PHP
print decbin(16);
print base_convert("16", 10, 2);
?>
base_convert("16", 10, 2)
is saying "convert the number 16
from base 10
to
base 2
.
The highest base that base_convert() supports is base 36, which uses 0?9 and then A?Z. If you try to use a base larger than 36, you will get an error.
The code above generates the following result.
Example 2
Convert a hexadecimal number to octal number:
<?php
$hex = "E196";
echo base_convert($hex,16,8);
?>
The code above generates the following result.
Example 3
Convert an octal number to a decimal number:
<?php
$oct = "0031";
echo base_convert($oct,8,10);
?>
The code above generates the following result.
Example 4
Convert an octal number to a hexadecimal number:
<?php
$oct = "364";
echo base_convert($oct,8,16);
?>
The code above generates the following result.