Instantly share code, notes, and snippets.

# tot-ra/gist:4251018 Created Dec 10, 2012

CRC calculations
 function crc16(\$string, \$crc = 0) { for(\$x = 0; \$x < strlen(\$string); \$x++) { \$crc = \$crc ^ ord(\$string[\$x]); echo \$crc . '
'; for(\$y = 0; \$y < 8; \$y++) { if((\$crc & 0x0001) == 0x0001) { \$crc = ((\$crc >> 1) ^ 0x10589); } else { \$crc = \$crc >> 1; } } } return \$crc; } function crc16_2(\$string) { \$crc = 0; for(\$x = 0; \$x < strlen(\$string); \$x++) { \$crc = \$crc ^ ord(\$string[\$x]); for(\$y = 0; \$y < 8; \$y++) { if((\$crc & 0x0001) == 0x0001) { \$crc = ((\$crc >> 1) ^ 0x8408); } else { \$crc = \$crc >> 1; } } } \$lb = (\$crc & 0xff00) >> 8; \$hb = (\$crc & 0x00ff) << 8; \$crc = \$hb | \$lb; return \$crc; } function crc16_3(\$data) { \$crc = 0xFFFF; for(\$i = 0; \$i < strlen(\$data); \$i++) { \$x = ((\$crc >> 8) ^ ord(\$data[\$i])) & 0xFF; \$x ^= \$x >> 4; \$crc = ((\$crc << 8) ^ (\$x << 12) ^ (\$x << 5) ^ \$x) & 0xFFFF; } return \$crc; } function crc16_4(\$string, \$crc = 0) { for(\$x = 0; \$x < strlen(\$string); \$x++) { \$crc = \$crc ^ ord(\$string[\$x]); for(\$y = 0; \$y < 8; \$y++) { if((\$crc & 0x0001) == 0x0001) { \$crc = ((\$crc >> 1) ^ 0xA001); } else { \$crc = \$crc >> 1; } } } return \$crc; } function crc16_5(\$string) { \$crc = 0xFFFF; for(\$x = 0; \$x < strlen(\$string); \$x++) { \$crc = \$crc ^ ord(\$string[\$x]); for(\$y = 0; \$y < 8; \$y++) { if((\$crc & 0x0001) == 0x0001) { \$crc = ((\$crc >> 1) ^ 0xA001); } else { \$crc = \$crc >> 1; } } } return \$crc; } function calculate_common_crc16c(\$buffer) { \$crc16c = 0xffff; // the crc initial value \$buffer_length = strlen(\$buffer); for(\$i = 0; \$i < \$buffer_length; \$i++) { \$ch = ord(\$buffer[\$i]); \$crc16c = update_common_crc16c(\$ch, \$crc16c); } return \$crc16c; } function update_common_crc16c(\$ch, \$crc16c) { global \$crc16c_polynomial; \$ch <<= 8; for(\$i = 0; \$i < 8; \$i++) { if((\$crc16c ^ \$ch) & 0x8000) { \$xor_flag = true; } else { \$xor_flag = false; } \$crc16c = \$crc16c << 1; if(\$xor_flag) { \$crc16c = \$crc16c ^ \$crc16c_polynomial; } \$ch = \$ch << 1; } // mask off (zero out) the upper two bytes \$crc16c = \$crc16c & 0x0000ffff; return \$crc16c; }