Last active
June 18, 2018 23:20
-
-
Save chingor13/e5b876e77a22f19dd0ba9ecfb5302a9a to your computer and use it in GitHub Desktop.
Testing base conversion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// $foo = "12524176338753030162"; | |
// $foo = "12524176338"; | |
$foo = $argv[1]; | |
function bcdechex($dec) { | |
$hex = ''; | |
do { | |
$last = bcmod($dec, 16); | |
$hex = dechex($last).$hex; | |
$dec = bcdiv(bcsub($dec, $last), 16); | |
} while($dec>0); | |
return $hex; | |
} | |
function my_base_convert($numstring, $frombase, $tobase) | |
{ | |
$chars = "0123456789abcdefghijklmnopqrstuvwxyz"; | |
$tostring = substr($chars, 0, $tobase); | |
$length = strlen($numstring); | |
$result = ''; | |
for ($i = 0; $i < $length; $i++) | |
{ | |
$number[$i] = strpos($chars, $numstring{$i}); | |
} | |
do | |
{ | |
$divide = 0; | |
$newlen = 0; | |
for ($i = 0; $i < $length; $i++) | |
{ | |
$divide = $divide * $frombase + $number[$i]; | |
if ($divide >= $tobase) | |
{ | |
$number[$newlen++] = (int)($divide / $tobase); | |
$divide = $divide % $tobase; | |
} elseif ($newlen > 0) | |
{ | |
$number[$newlen++] = 0; | |
} | |
} | |
$length = $newlen; | |
$result = $tostring{$divide} . $result; | |
} while ($newlen != 0); | |
return $result; | |
} | |
function time_function(callable $func, $times = 1000) { | |
$c = new HRTime\StopWatch(); | |
$results = []; | |
for ($i = 0; $i < $times; $i++) { | |
$c->start(); | |
$res = $func(); | |
$c->stop(); | |
$results[] = $c->getLastElapsedTime(HRTime\Unit::NANOSECOND); | |
} | |
echo 'average: ' . array_sum($results) / count($results) . PHP_EOL; | |
var_dump($res); | |
} | |
echo "dechex\n"; | |
time_function(function () use ($foo) { | |
return dechex($foo); | |
}); | |
echo "bcchex\n"; | |
time_function(function () use ($foo) { | |
return bcdechex($foo); | |
}); | |
echo "custom\n"; | |
time_function(function () use ($foo) { | |
return my_base_convert($foo, 10, 16); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment