10-16
<?php
function dec2hex($str){
$hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
$hexval = '';
$quotient = $str;
$divisor = $str;
$flag = true;
while($flag)
{
$len = strlen($divisor);
$pos = 1;
$quotient = 0;
$div = substr($divisor, 0, 2);
$remainder = $div[0];
while($pos < $len)
{
$div = $remainder == 0 ? $divisor[$pos] : $remainder.$divisor[$pos];
$remainder = $div % 16;
$quotient = $quotient.floor($div/16);
$pos++;
}
$quotient = trim_left_zeros($quotient);
$divisor = "$quotient";
$hexval = $hex[$remainder].$hexval;
if (strlen($divisor)<=2)
{
if ($divisor<15)
{
$flag = false;
}
}
}
$hexval = $hex[$quotient].$hexval;
$hexval = trim_left_zeros($hexval);
return $hexval;
}
function trim_left_zeros($str)
{
$str = ltrim($str, '0');
if (empty($str))
{
$str = '0';
}
return $str;
}
$hex = dec2hex('10153302696068');
if($hex%2!=0) $hex = '0'. $hex;
$str = str_split($hex,2);
$out = '';
for($i=0;$i<count($str);$i++)
{
$out = '\x' . $str[$i] . $out;
}
$out = $out.'\x00\00';
echo $out;
?>
16-10
<?php
function convBase($numberInput, $fromBaseInput, $toBaseInput)
{
if ($fromBaseInput==$toBaseInput) return $numberInput;
$fromBase = str_split($fromBaseInput,1);
$toBase = str_split($toBaseInput,1);
$number = str_split($numberInput,1);
$fromLen=strlen($fromBaseInput);
$toLen=strlen($toBaseInput);
$numberLen=strlen($numberInput);
$retval='';
if ($toBaseInput == '0123456789')
{
$retval=0;
for ($i = 1;$i <= $numberLen; $i++)
$retval = bcadd($retval, bcmul(array_search($number[$i-1], $fromBase),bcpow($fromLen,$numberLen-$i)));
return $retval;
}
if ($fromBaseInput != '0123456789')
$base10=convBase($numberInput, $fromBaseInput, '0123456789');
else
$base10 = $numberInput;
if ($base10<strlen($toBaseInput))
return $toBase[$base10];
while($base10 != '0')
{
$retval = $toBase[bcmod($base10,$toLen)].$retval;
$base10 = bcdiv($base10,$toLen,0);
}
return $retval;
}
$btime = microtime(true);
echo convBase('c4ca4238a0b923820dcc509a6f75849b', '0123456789abcdef', '0123456789');
echo microtime(true) - $btime;
?>