프로그래밍/JAVA

CRC16-CCITT crc생성함수

chance 2012. 10. 4. 19:45

Reference : http://introcs.cs.princeton.edu/java/51data/CRC16CCITT.java

 

 

additional 

1. ascii string to hex value

2. reverse bits

3. last xor : 0xffff

4. crc byte-order

 

public static String makeCRC16_CCITT( String hexString, boolean isReverse) throws Exception {

   int len = hexString.length();

   if( len % 2 != 0 ) {

      throw new Exception("HEX format exception");

   }

 

   byte[] input = hexString.getBytes();

   byte[] hex = new byte[input.length/2];

   // 2bytes ascii code -> 1byte value

   int cnt=0;

   for( int i=0; i<input.length; i+=2 ) {

      int val1 = Character.getNumericValue(input[i]);

      int val2 = Character.getNumericValue(input[i+1]);

      if( val1 < 0 || val2 < 0 ) {

          throw new Exception("HEX format exception");

      }

      

      hex[cnt] = (byte) ((val1<<4) + val2);

   }

   // Reflected In

   if( isReverse ) {

      for( int i=0; i<hex.length; i++ ) {

      

         int in = (int) (hex[i]&0xff);

         int temp = 0;

         int out = 0;

        

         for( int j=0; j<8; j++ ) {

            temp = (in>>j)&0x01;

            out = (out << 1) + temp;

         }

        

         hex[i] = (byte) out;

      }

   }

   // Initialization value

   int crc = 0xFFFF;

   // Polynomial

   int polynomial = 0x1021;

        

   // CRC

   for (byte b : hex) {

      for (int i = 0; i < 8; i++) {

         boolean bit = ((b   >> (7-i) & 1) == 1);

         boolean c15 = ((crc >> 15    & 1) == 1);

         crc <<= 1;

         if (c15 ^ bit) crc ^= polynomial;

      }

   }

 

        

   // Reflected Out : reverse crc bits

   if( isReverse ) {

      int temp = 0;

      int out = 0;

      for( int i=0; i<16; i++ ) {

         temp = (crc>>i)&0x01;

         out = (out << 1) + temp;

      }

      crc = out;

   }

        

   crc&=0xffff;

        

        

        

   // last xor

   crc = crc^0xffff;

        

   // big-endian to little-endian

   int temp = (crc>>8) & 0xff;

   crc = ((crc&0xff)<<8 ) + temp;

        

    return Integer.toHexString(crc);

}