Tuesday, March 8, 2016

CRC16 Calculator using JAVA

           CRC codes are numerously used fro error checking purposes. So many times working around Embedded Devices you will find CRC used in different communication protocols. So guys here i have written a piece of code to generate CRC16 using provid
ed packets in JAVA.

CODE:

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);  
   }
}

No comments:

Post a Comment