2

To expand and give explanation that may also go with the link posted above, here is a function in PHP for getting a CRC16 checksum for string data:

    function crc16($data) {
        $crc = 0xAC6F;
        $len = strlen($data);
        $i = 0;
        while ($len--) {
            $crc ^= reversebyte(ord($data[$i++])) << 8;
            $crc &= 0xffff;
            for ($j = 0; $j < 8; $j++){
                $crc = ($crc & 0x8000) ? ($crc << 1) ^ 0x8005 : $crc << 1;
                $crc &= 0xffff;
            }
        }
        $crc ^= 0x0000;
        $crc = reversebits($crc);
        return $crc;
    }

    function reversebyte($byte) {
        $ob = 0;
        $b = (1 << 7);
        for ($i = 0; $i <= 7; $i++) {
            if (($byte & $b) !== 0) {
                $ob |= (1 << $i);
            }
            $b >>= 1;
        }
        return $ob;
    }

    function reversebits($cc) {
        $ob = 0;
        $b = (1 << 15);
        for ($i = 0; $i <= 15; $i++) {
            if (($cc & $b) !== 0) {
                $ob |= (1 << $i);
            }
            $b >>= 1;
        }
        return $ob;
    }

    Poly = 0x8005
    Init = 0xAC6F
    Xor = 0x0000
    Refin = True
    Refout = True

If you don't want to add reflection then replace these lines in function crc16():

Replace Refin = True:

    $crc ^= reversebyte(ord($data[$i++])) << 8;

With Refin = False:

    $crc ^= ord($data[$i++]) << 8;

Replace Refout = True:

    $crc = reversebits($crc);

with Refout = False (remove this whole line):

    $crc = reversebits($crc); //remove me
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
user3282492
  • 29
  • 1
  • 5

1 Answers1

0

To write your own CRC function, I recommend you read The Painless Guide to CRC Error Detection Algorithms. It provides pseudo-code for different kind of implementations, including a simple, naive one and improved table-driven implementations. The guide also covers your requirements such as refin, refout and so on.

The only real difficulty left is then to translate the pseudo-code or the C code to php, but since php has just the same bitwise operators as C, this shouldn't really be a challenge.

Geier
  • 894
  • 7
  • 16