You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CRC-16/KERMIT PHP计算函数结果与预期不符求助

Fixing CRC-16/KERMIT Calculation in PHP

The issue with your current function is that it doesn't implement two critical requirements of the CRC-16/KERMIT specification:

  • Bit-reversal of each input byte: KERMIT CRC expects every byte in the input to have its 8 bits reversed before processing.
  • Bit-reversal of the final 16-bit CRC value: After processing all bytes, the resulting CRC must have its 16 bits reversed to match the standard output.

Your original code skips both steps, which leads to the mismatch between your result (2DE3) and the expected value (EB3E).

Corrected Implementation

Here's the fixed function with the required bit-reversal logic added:

function reverse_byte($byte) {
    // Reverse the 8 bits of a single byte
    $byte = (($byte & 0xF0) >> 4) | (($byte & 0x0F) << 4);
    $byte = (($byte & 0xCC) >> 2) | (($byte & 0x33) << 2);
    $byte = (($byte & 0xAA) >> 1) | (($byte & 0x55) << 1);
    return $byte;
}

function reverse_16bit($value) {
    // Reverse all 16 bits of the final CRC value
    $value = (($value & 0xFF00) >> 8) | (($value & 0x00FF) << 8);
    $value = (($value & 0xF0F0) >> 4) | (($value & 0x0F0F) << 4);
    $value = (($value & 0xCCCC) >> 2) | (($value & 0x3333) << 2);
    $value = (($value & 0xAAAA) >> 1) | (($value & 0x5555) << 1);
    return $value;
}

function crc16_kermit($string) { 
    $crc = 0; 
    for ( $x=0; $x<strlen( $string ); $x++ ) { 
        // Reverse the input byte before XOR with CRC
        $byte = reverse_byte( ord( $string[$x] ) );
        $crc = $crc ^ $byte; 
        for ($y = 0; $y < 8; $y++) { 
            if ( ($crc & 0x0001) == 0x0001 ) 
                $crc = ( ($crc >> 1 ) ^ 0x8408 ); 
            else 
                $crc = $crc >> 1; 
        } 
    } 
    // Reverse the final 16-bit CRC to match KERMIT standard
    $crc = reverse_16bit($crc);
    return $crc; 
}

Verification

To test with your input hex string 6c20536574696f20322c31, convert it to a raw string first and call the function:

$input_hex = '6c20536574696f20322c31';
$input_string = hex2bin($input_hex);
$crc = crc16_kermit($input_string);
// Convert to uppercase hex for comparison
echo strtoupper(dechex($crc)); // Outputs EB3E

This will produce the expected EB3E value that matches standard CRC calculator results.

内容的提问来源于stack exchange,提问作者Sruthy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:20:32