# php - 具有 poly x^16 + x^10 + x^8 + x^7 + x^3 + 1的php CRC 16 DECT

``````
x^16 + x^10 + x^8 + x^7 + x^3 + 1

``````

``````
function crc16(\$string,\$crc=0) {

for ( \$x=0; \$x<strlen( \$string ); \$x++ ) {

\$crc = \$crc ^ ord( \$string[\$x] );

echo \$crc.'<br/>';

for (\$y = 0; \$y <8 ; \$y++) {

if ( (\$crc & 0x0001) == 0x0001 ) \$crc = ( (\$crc>> 1 ) ^ 0x10589 );

else \$crc = \$crc>> 1;

}

}

return \$crc;

}

echo 'CRC:'.crc16('10100011');

``````

``````
polynomial coefficients

|

| 10100010 <--- quotient (irrelevant)

v __________

10000010110001001 ) 10100011 <-------- input

^ 10000010110001001

-----------------

= 100001110001001

^ 10000010110001001

-----------------

= 101110101101

^ 10000010110001001

-----------------

remainder (CRC) -----> = 111000000101001

= 0x7029 = 28713

``````

``````
#include <stdio.h>

#include <stdint.h>

static uint16_t crc16(const uint8_t *data, size_t len)

{

size_t i, j;

uint16_t crc = 0;

for (i = 0; i <len; i++) {

crc ^= (data[i] <<8);/* data at top end, not bottom */

for (j = 0; j <8; j++) {

if ((crc & 0x8000) == 0x8000)/* top bit, not bottom */

crc = (crc <<1) ^ 0x0589;/* shift left, not right */

else

crc <<= 1;/* shift left, not right */

}

}

return crc;

}

int main(void)

{

const uint8_t in[] = { 0xa3 };/* = 10100011 in binary */

uint16_t crc = crc16(in, sizeof(in));

printf("%u (0x%x)n", crc, crc);

return 0;

}

``````

``````
\$ gcc -Wall -o crc16 crc16.c

\$./crc16

28713 (0x7029)

\$

``````