Converting 8 bit CRC function written in C to PHP -
i trying convert c function php 8 bit crc calculation.
the original c code:
uint8_t crccalc (uint8_t* pointer, uint16_t len) { uint8_t crc = 0x00; uint16_t tmp; while(len > 0) { tmp = crc << 1; tmp += *pointer; crc = (tmp & 0xff) + (tmp >> 8); pointer++; --len; } return crc; } the php code have come is:
function crc8_calc($hex_string) { $bin_data = pack('h*',$hex_string); $bin_length = strlen($bin_data); $crc = 0x00; $pos = 0; while($bin_length>0) { //$pos = $crc << 1; $crc = ($bin_data[$pos] & 0xff) + ($bin_data[$pos] >> 8); $bin_length --; $pos++ ; } return $crc; } there missing results php functions not correct. not familiar c, not sure if conversion correct. c function gives out correct crc
for example, if hex representation of string is: 280500000805151001240000000010017475260004041001372068828503000000000000
the crc should d4.
i have seen following links crc8 calculation, seem missing something
how generate 8bit crc in php crc8-check in php
i have taken bits of conversion code answer convert c php crc16 function
try this:
function crc8_calc($hex_string) { $bin_data = pack('h*',$hex_string); $bin_length = strlen($bin_data); $crc = 0; $tmp = 0; $pos = 0; while($bin_length>0) { $tmp = $crc << 1; $tmp = $tmp + ord($bin_data[$pos]); //added ord $crc = ($tmp + ($tmp >> 8)) & 0xff; $bin_length --; $pos++ ; } return $crc; }
Comments
Post a Comment