CRC16算法三种语言的实现
Implementation of CRC16 in three languages
2021-06-15 17:52:03
Algorithm
204

crc16算法结果为:crc16("The quick brown fox jumps over the lazy dog")=19805,0x4d5d

C语言实现

#include <stdio.h>

typedef unsigned char u_char;
typedef unsigned int uint32_t;

static void jv_crc16_update(const u_char c, uint32_t *value){
    int a, b,count;
    uint32_t t=*value;

        a = (int) c;
        for (count = 7; count >=0; count--) {
            a = a << 1;
            b = (a >> 8) & 1; /* a >>> 8 in java  */
            if ((t & 0x8000) != 0) {
                t = ((t<< 1) + b) ^ 0x1021;
            } else {
                t = (t << 1) + b;
            }
        }
        *value = t & 0xffff;
}
uint32_t jv_crc16(const u_char *data, size_t n){
    uint32_t v=0x0;

    for (; n; n--) {
        u_char c = *data++;
        jv_crc16_update(c, &v);
    }

    return v;
}
int main() {
 u_char a[] = "The quick brown fox jumps over the lazy dog";
 uint32_t v = jv_crc16(a, sizeof(a)-1);
 printf("crc16(\"%s\")=%u,%#0x\n", a, v, v);
 return 0;
}

PHP语言实现

function crc16( $data ) {
    $value = 0;
    $n = strlen( $data );
    for ( $i = 0; $i< $n ; $i++ ) {
        $a = ord( $data[$i] );
        for ( $count = 7; $count >=0; $count-- ) {
            $a = $a << 1;
            $b = ( $a >> 8 ) & 1;
            if ( ( $value & 0x8000 ) != 0 ) {
                $value = ( ( $value << 1 ) +$b ) ^ 0x1021;
            } else {
                $value = ( $value << 1 ) + $b;
            }
        }
        $value = $value & 0xffff;
    }
    return $value;
}
echo dechex( crc16( $data ) );

Java语言实现(JDK中的实现为:sun.misc.CRC16)

/**
 * The CRC-16 class calculates a 16 bit cyclic redundancy check of a set
 * of bytes. This error detecting code is used to determine if bit rot
 * has occurred in a byte stream.
 */

public class CRC16 {

    /** value contains the currently computed CRC, set it to 0 initally */
    public int value;

    public CRC16() {
        value = 0;
    }

    /** update CRC with byte b */
    public void update(byte aByte) {
        int a, b;

        a = (int) aByte;
        for (int count = 7; count >=0; count--) {
            a = a << 1;
            b = (a >>> 8) & 1;
            if ((value & 0x8000) != 0) {
                value = ((value << 1) + b) ^ 0x1021;
            } else {
                value = (value << 1) + b;
            }
        }
        value = value & 0xffff;
        return;
    }

    /** reset CRC value to 0 */
    public void reset() {
        value = 0;
    }
}

 public static void main(String[] args) throws IOException {

  String s = "The quick brown fox jumps over the lazy dog";

  CRC16 crc16 = new CRC16();
  byte[] data = s.getBytes();
  for (int i = 0; i < data.length; i++) {
   crc16.update(data[i]);
  }
  System.out.println(crc16.value);
  System.out.println(Integer.toHexString(crc16.value));
 }