Home > Net >  I would like to change a string of numbers of length 54 characters from base 10 to base 16 in js or
I would like to change a string of numbers of length 54 characters from base 10 to base 16 in js or

Time:03-29

<?php
    function base16($str){
        $str = base_convert($str,10,16);
        echo $str;
    }
    base16("000012345678920190113163721231000011101000000000100001");

    //8727f63a15f8a0000000000000000000000000000
?>

I have this number array in base 10

000012345678920190113163721231000011101000000000100001

and the expected result should be

8727F63A15F8976591FDDE5B387C5D015A29E06A1

CodePudding user response:

You can use BigInt to solve this in JS

console.log(
  BigInt(
      "000012345678920190113163721231000011101000000000100001"
  ).toString(16)
)

CodePudding user response:

You can try this-

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;
}
?>

Then

<?php
convBase('000012345678920190113163721231000011101000000000100001', '0123456789', '0123456789ABCDEF');
?>

parameters->

dataToConvert
fromBase
toBase

CodePudding user response:

Can you use GMP ?

<?php
$str = '000012345678920190113163721231000011101000000000100001';
echo strtoupper(gmp_strval(gmp_init($str, 10), 16));
// 8727F63A15F8976591FDDE5B387C5D015A29E06A1
  • Related