Convert milliseconds to 16-digit hexadecimal

2

I am implementing an algorithm to generate a key access to a certain system, however the need to convert a numeric value to 16-digit hexadecimal.

Consider the number of milliseconds since January 1, 1970:

$milliseconds = (time()*1000);
//1530747443000

Is it possible to convert the value in milliseconds to a 16-digit hexadecimal value?

    
asked by anonymous 05.07.2018 / 01:38

2 answers

3

According to the documentation , dechex() only supports integers with values up to 4294967295 .

In this case, you need to write a function that can convert large integers to hexadecimal, see:

<?php

function bcdechex($dec) {
    $hex = '';
    do {    
        $last = bcmod($dec, 16);
        $hex = dechex($last).$hex;
        $dec = bcdiv(bcsub($dec, $last), 16);
    } while($dec>0);
    return str_pad($hex, 16, "0", STR_PAD_LEFT);
}

$hexstr = bcdechex( time() * 1000 );

echo $hexstr;

?>

Output:

0000016467d83520
    
05.07.2018 / 02:04
1

You can use Math/BigInteger to solve your problem and easily create a hexadecimal converter:

<?php

include('Math/BigInteger.php');

function toHex($n) {
    $zero = new Math_BigInteger(0);
    if ($n->compare($zero) == 0) return "0";
    $base = "0123456789ABCDEF";
    $dezesseis = new Math_BigInteger(16);
    $result = "";
    while ($n->compare($zero) > 0) {
        list($n, $r) = $n->divide($dezesseis);
        $result = $base[intval($r->toString())] . $result;
    }
    return $result;
}

function milliToHex() {
    $temp = new Math_BigInteger(time());
    $mil = new Math_BigInteger(1000);
    $ret = toHex($temp->multiply($mil));
    return str_pad($ret, 16, "0", STR_PAD_LEFT);
}

echo milliToHex();

?>

For me, it produced this output:

0000016468976E40

See here working on ideone (but do not be alarmed at the size of the code, as I had to copy and paste the whole Math/BigInteger class there in the ideone).

I've already done this answer three and a half years ago using some similar concepts.

    
05.07.2018 / 06:06