base_convert
Description
The base_convert of Math for PHP convert a number between arbitrary bases.
Syntax
base_convert(
string $num,
int $from_base,
int $to_base
): stringParameters
num
The number to convert. Any invalid characters in num are silently ignored.
from_base
The base num is in.
to_base
The base to convert num to.
Return
Returns num converted to base to_base
Examples
1 · num from_base to_base
<? $num = 16; $from_base = 10; $to_base = 2; $return = base_convert($num, $from_base, $to_base); echo $return;
10000
2 · from decimal to binary
<?
for($i = 0; $i < 16; ++$i)
{
$num = $i;
$from_base = 10;
$to_base = 2;
$return = base_convert($num, $from_base, $to_base);
echo $num . ":" . $return . PHP_EOL;
}
0:0 1:1 2:10 3:11 4:100 5:101 6:110 7:111 8:1000 9:1001 10:1010 11:1011 12:1100 13:1101 14:1110 15:1111
3 · from decimal to octal
<?
for($i = 0; $i < 16; ++$i)
{
$num = $i;
$from_base = 10;
$to_base = 8;
$return = base_convert($num, $from_base, $to_base);
echo $num . ":" . $return . PHP_EOL;
}
0:0 1:1 2:2 3:3 4:4 5:5 6:6 7:7 8:10 9:11 10:12 11:13 12:14 13:15 14:16 15:17
4 · from decimal to hexadecimal
<?
for($i = 0; $i < 16; ++$i)
{
$num = $i;
$from_base = 10;
$to_base = 16;
$return = base_convert($num, $from_base, $to_base);
echo $num . ":" . $return . PHP_EOL;
}
0:0 1:1 2:2 3:3 4:4 5:5 6:6 7:7 8:8 9:9 10:a 11:b 12:c 13:d 14:e 15:f