0

I have this string:

000480741401920220327110158164000021101000000005100019

And I have to convert it into a hexadecimal using PHP, it looks pretty easy.

So I did that in several ways, but it turns always wrong.

First I tried using this PHP function:

decbin(000480741401920220327110158164000021101000000005100019)

And I have this result:

303030343830373431343031393230323230333237313130313337313634303030303231313031303030303030303035313030303139

I felt happy, but the answer it's wrong for some reason. Then I tried this function

base_convert(000480741401920220327110158164000021101000000005100019, 10, 16)

And I have the same result. Then I tried many solutions on the internet like

private function string2ByteArray($string) {
    return unpack('C*', $string);
}

private function byteArray2Hex($byteArray) {
    $chars = array_map("chr", $byteArray);
    $bin = join($chars);
    return bin2hex($bin);
}

Using both functions, and always I received the same answer. Finally I found this website:

https://wims.univ-cotedazur.fr/wims/wims.cgi

And I tried the same data and finally I have the correct answer:

148EFC6062103B563DD35B3BF79036E274291D251F3

And I'm triyng to replicate the same answer by several hours, but I can't.

I tried many other "solutions"

private function strhexbyte($string)
{
    $bytes = array();
    for($i=0,$l = strlen($string);$i<$l;$i++)
    {
        $bytes[] = dechex(ord($string[$i]));
    }
    return implode($bytes);
}

Also:

private function strhex($string) {
    $hexstr = unpack('H*', $string);
    return array_shift($hexstr);
}

But always found the same wrong answer. I'm not sure what am I doing wrong, please give me a hand.

Regards

Lenny
  • 1
  • The accepted answer explains everything, including that the issue is that [the largest number that can be converted is 4294967295](http://php.net/manual/en/function.dechex.php#refsect1-function.dechex-description) – Andrea Olivato Mar 27 '22 at 15:34

1 Answers1

0

This seems to work, I got the inspiration from this questions and this answer

However to get it to work in PHP8 there are a couple of mods required as shown below.

$dec = '480741401920220327110158164000021101000000005100019';
function bcdechex($dec) {
    $hex = '';
    do {    
        $last = (int) bcmod($dec, '16');
        $hex = dechex($last).$hex;
        $dec = bcdiv(bcsub($dec, (string)$last), '16');
    } while($dec > 0);
    return $hex;
}
echo bcdechex($dec);
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149