CRC codes are numerously used for error checking purposes. So many times working around Embedded Devices you will find CRC used in different communication protocols for error detection. This piece of code will help you to generate CRC16 using provided packets in JAVA. While working on devices like Raspberry Pi which supports JAVA and industrial protocols like MODBUS which uses CRC16, this code can be used.
The calculateCrc16 class defines 3 functions with CalculateCRC16 function taking the input buffer of which the CRC has to be calculated. The getHCrc and getLCrc functions return the MSB and LSB of the calculated CRC respectively.
package crcCalculator; public class calculateCrc16 { long hb_CRC; long lb_CRC; public long getHCrc(){// Returns High byte of CRC return this.hb_CRC; } public long getLCrc(){// Returns Low byte of CRC return this.lb_CRC; } public static void main(String[] args){ char[] buf={(char)1,(char)4,(char)4,(char)0,(char)1,(char)46};// Packets for which //CRC is to be calculated calculateCrc16 c16=new calculateCrc16(); c16.CalculateCRC16(buf); System.out.println( c16.getHCrc()+" "+c16.getLCrc()); } public void CalculateCRC16(char[] buf){ long crc = 0xFFFF; for (int pos = 0; pos < buf.length; pos++){ crc ^= (long)buf[pos]; for (int i = 8; i != 0; i--){ if ((crc & 0x0001) != 0) { crc >>= 1; crc ^= 0xA001; } else crc >>= 1; } } lb_CRC= (crc & 65280)>>8; hb_CRC= (crc & 255); } }