欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

[转]PHP下CRC64算法实现

程序员文章站 2022-09-05 08:32:25
本文转自PHP官方文档中大佬回复: https://www.php.net/manual/en/function.crc32.php

本文转自php官方文档中大佬回复:

[转]PHP下CRC64算法实现

 

 

<?php

/**
* @return array
*/
function crc64table()
{
    $crc64tab = [];

    // ecma polynomial
    $poly64rev = (0xc96c5795 << 32) | 0xd7870f42;

    // iso polynomial
    // $poly64rev = (0xd8 << 56);

    for ($i = 0; $i < 256; $i++)
    {
        for ($part = $i, $bit = 0; $bit < 8; $bit++) {
            if ($part & 1) {
                $part = (($part >> 1) & ~(0x8 << 60)) ^ $poly64rev;
            } else {
                $part = ($part >> 1) & ~(0x8 << 60);
            }
        }

       $crc64tab[$i] = $part;
    }

    return $crc64tab;
}

/**
* @param string $string
* @param string $format
* @return mixed
*
* formats:
*  crc64('php'); // afe4e823e7cef190
*  crc64('php', '0x%x'); // 0xafe4e823e7cef190
*  crc64('php', '0x%x'); // 0xafe4e823e7cef190
*  crc64('php', '%d'); // -5772233581471534704 signed int
*  crc64('php', '%u'); // 12674510492238016912 unsigned int
*/
function crc64($string, $format = '%x')
{
    static $crc64tab;

    if ($crc64tab === null) {
        $crc64tab = crc64table();
    }

    $crc = 0;

    for ($i = 0; $i < strlen($string); $i++) {
        $crc = $crc64tab[($crc ^ ord($string[$i])) & 0xff] ^ (($crc >> 8) & ~(0xff << 56));
    }

    return sprintf($format, $crc);
}