We can use base_convert() to convert binary directly to hexadecimal, or octal to duodecimal (base 12) or hexadecimal to vigesimal (base 20).
PHP base_convert() function's format is as follows.
string base_convert ( string num, int from_base , int to_base )
base_convert()
takes three parameters:
a number to convert,
the base to convert from, and
the base to convert to.
The return value is the number converted to the specified base. The return type is String.
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.
Convert a hexadecimal number to octal number:
<?php
$hex = "E196";
echo base_convert($hex,16,8);
?>
The code above generates the following result.
Convert an octal number to a decimal number:
<?php
$oct = "0031";
echo base_convert($oct,8,10);
?>
The code above generates the following result.
Convert an octal number to a hexadecimal number:
<?php
$oct = "364";
echo base_convert($oct,8,16);
?>
The code above generates the following result.