zhubaomin
2024-12-02 5fcdef2e8eec55221bb65a7a2cf91a4be7cc89ac
pipIrr-platform/pipIrr-common/src/main/java/com/dy/common/util/CRC16.java
@@ -1,6 +1,8 @@
package com.dy.common.util;
import com.dy.common.mw.protocol.p206V1.ProtocolConstantV206V1;
@SuppressWarnings("unused")
public final class CRC16 {
   
@@ -50,9 +52,8 @@
   }
   
   
    private static final int[] crc16_rev_table = new int[]
       {   0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
   private static final int[] crc16_rev_table = new int[]{
      0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
          0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
          0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
          0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
@@ -87,18 +88,36 @@
           };
   /**
    * 16位的CRC值是无符号两字节整数,
    * @param bs 字节数组
    * @param startIndex 开始下标
    * @param endIndex 截止下标
    * @return CRC
    */
   @SuppressWarnings("unused")
   public int CRC16_table(byte[] bs, int startIndex, int endIndex) {
      int x ;
      int crc = 0xffff;
      if(bs != null && bs.length >= endIndex + 1){
         for (int i = startIndex ; i <= endIndex; i++){
            x =  (crc ^ bs[i]) ;
            crc =  ((crc >> 8) ^ crc16_rev_table[x & 0x00FF]) ;
         }
      }
      return crc ;
   }
   /**
    * 16位的CRC值 ,查表法
    * @param bs 字节数组
    * @return CRC
    */
   @SuppressWarnings("unused")
   public int CRC_table(byte[] bs) {
      int x ;
      int crc = 0xffff;
   public short CRC16_table(byte[] bs) {
      short x ;
      short crc = (short)0xffff;
      if(bs != null && bs.length > 0){
         for(byte b : bs){
            x = crc ^ b ;
            crc = (crc >> 8) ^ crc16_rev_table[x & 0x00FF];
            x = (short)(crc ^ b) ;
            crc = (short)((crc >> 8) ^ crc16_rev_table[x & 0x00FF]) ;
         }
      }
      return crc ;
@@ -122,5 +141,15 @@
      return crc;
   }
   
   public static void main(String[] args) throws Exception {
      int s = 62430 ;
      //String hex = "AA0018AA16015301150599800001100000014A005D4D5D4D00004000AA7E16" ;
      String hex = "AA0018AA16015301150599800001100000014A005D4D5D4D00004000" ;
      byte[] bs = ByteUtil.hex2Bytes(hex) ;
      int crc = new CRC16().CRC16_table(bs, 0 , bs.length - 1) ;
      byte[] crcBs = new byte[4] ;
      ByteUtil.int2Bytes_BE(crcBs, crc, 0);
      System.out.println(ByteUtil.bytes2Hex(crcBs, true)) ;
   }
}