PHP 8.4.24 Released!

Voting

: four plus three?
(Example: nine)

The Note You're Voting On

JS at JavsSys dot Org
13 years ago
The khash() function by sukitsupaluk has two problems, it does not use all 62 characters from the $map set and when corrected it then produces different results on 64-bit compared to 32-bit PHP systems.

Here is my modified version :

<?php

/**
 * Small sample convert crc32 to character map
 * Based upon http://www.php.net/manual/en/function.crc32.php#105703
 * (Modified to now use all characters from $map)
 * (Modified to be 32-bit PHP safe)
 */
function khash($data)
{
    static $map = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $hash = bcadd(sprintf('%u',crc32($data)) , 0x100000000);
    $str = "";
    do
    {
        $str = $map[bcmod($hash, 62) ] . $str;
        $hash = bcdiv($hash, 62);
    }
    while ($hash >= 1);
    return $str;
}
//-----------------------------------------------------------------------------------
$test = array(null, true, false, 0, "0", 1, "1", "2", "3", "ab", "abc", "abcd",
    "abcde", "abcdefoo", "248840027", "1365848013", // time()
    "9223372035488927794", // PHP_INT_MAX-time()
    "901131979", // mt_rand()
    "Sat, 13 Apr 2013 10:13:33 +0000" // gmdate('r') 
);
$out = array();
foreach ($test as $s)
{
    $out[] = khash($s) . ": " . $s;
}
print "<h3>khash() -- maps a crc32 result into a (62-character) result</h3>";
print '<pre>';
var_dump($out);
print "\n\n\$GLOBALS['raw_crc32']:\n";
var_dump($GLOBALS['raw_crc32']);
print '</pre><hr>';
flush();
$pefile = __FILE__;
print "<h3>$pefile</h3>";
ob_end_flush();
flush();
highlight_file($pefile);
print "<hr>";
//-----------------------------------------------------------------------------------
/* CURRENT output
array(19) {
  [0]=>
  string(8) "4GFfc4: "
  [1]=>
  string(9) "76nO4L: 1"
  [2]=>
  string(8) "4GFfc4: "
  [3]=>
  string(9) "9aGcIp: 0"
  [4]=>
  string(9) "9aGcIp: 0"
  [5]=>
  string(9) "76nO4L: 1"
  [6]=>
  string(9) "76nO4L: 1"
  [7]=>
  string(9) "5b8iNn: 2"
  [8]=>
  string(9) "6HmfFN: 3"
  [9]=>
  string(10) "7ADPD7: ab"
  [10]=>
  string(11) "5F0aUq: abc"
  [11]=>
  string(12) "92kWw9: abcd"
  [12]=>
  string(13) "78hcpf: abcde"
  [13]=>
  string(16) "9eBVPB: abcdefoo"
  [14]=>
  string(17) "5TjOuZ: 248840027"
  [15]=>
  string(18) "5eNliI: 1365848013"
  [16]=>
  string(27) "4Q00e5: 9223372035488927794"
  [17]=>
  string(17) "6DUX8V: 901131979"
  [18]=>
  string(39) "5i2aOW: Sat, 13 Apr 2013 10:13:33 +0000"
}
*/
//-----------------------------------------------------------------------------------

?>

<< Back to user notes page

To Top