Joke Collection Website - Public benefit messages - What is the CRC algorithm in Java?

What is the CRC algorithm in Java?

There are two methods to implement the CRC algorithm, one is the look-up table method, and the other is direct calculation. The calculation speed of the look-up table method is relatively fast. The method I introduced is the direct calculation method, which uses 2 This method is implemented by encapsulating the algorithm in an object-oriented manner.

package com.wms.serial;

/**

* @author linduo

* @version 2006/08/25

*/

public class CRC16{

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 gt ;=0; count--) {

a = a lt; lt; 1;

b = (a gt; gt; gt; 8) amp; 1;

p>

if ((value amp; 0x8000) != 0) {

value = ((value lt; lt; 1) b) ^ 0x1021;

} else {

value = (value lt; lt; 1) b;

}

}

value = value amp; 0xffff;

return;

}

/** reset CRC value to 0 */

public void reset()

{

value = 0;

}

public int getValue()

{

return value;

}

public static void main(String[] args) {

CRC16 crc16 = new CRC16();

byte[] b = new byte[]{

//(byte) 0xF0, (byte)0xF0, (byte)0xF0, (byte)0x72

(byte) 0x2C , (byte)0x00, (byte)0xFF, (byte)0xFE

, (byte) 0xFE, (byte)0x04, (byte)0x00, (byte)0x00

, (byte) 0x00, (byte)0x00

};

for (int k = 0; k lt; b.length; k )

{

crc16.update(b[k]);

> }

System.out.println(Integer.toHexString(crc16.getValue()));

System.out.println(Integer.toHexString(b.length));

}

}

package com.wms.serial;

public class CRC162 {

public static final void main(String[] args){

CRC162 crc16 = new CRC162();

byte[] b = new byte[]{

/ /(byte) 0xF0, (byte)0xF0, (byte)0xF0, (byte)0x72

(byte) 0x2C, (byte)0x00, (byte)0xFF, (byte)0xFE

, (byte) 0xFE, (byte)0x04, (byte)0x00, (byte)0x00

, (byte) 0x00, (byte)0x00

};

System.out.println(Integer.toHexString(crc16.encode(b)));

//Replace this 2f49 with the last two bytes of the b array , generate a new array b2

byte[] b2 = new byte[]{

//(byte) 0xF0, (byte)0xF0, (byte)0xF0, (byte )0x72

(byte) 0x2C, (byte)0x00, (byte)0xFF, (byte)0xFE

, (byte) 0xFE, (byte)0x04, (byte)0x00 , (byte)0x00

, (byte) 0x2f, (byte)0x49

};

System.out.println(Integer.toHexString(crc16. encode(b2))); //The calculated value is 0

//You can construct some bytes to try encryption and decryption

}

public short encode(byte[] b){

short CRC_x = 0;

int pp = 65536; // 1lt; lt; 16;

int pp2 = 69665; // (1lt;lt;16) (1lt;lt;12) (1lt;lt;5) 1

for(int i=0;ilt;b.length;i){

for(int j=0;jlt;8;j){

CRC_x = (short)((CRC_xlt;lt;1) (((b[i]lt;lt ;j)amp;0x80)gt;gt;7)

);

if((CRC_x/pp) == 1){

CRC_x=(short)(CRC_x^pp2);

}

}

}

return CRC_x;

}

}