package com.hb.proj.gather.utils; import java.util.ArrayList; import java.util.List; public class Crc16Utils { /** * 一个字节包含位的数量 8 */ private static final int BITS_OF_BYTE = 8; /** * 多项式 */ private static final int POLYNOMIAL = 0xA001; /** * 初始值 */ private static final int INITIAL_VALUE = 0xFFFF; /** * CRC16 编码 * @param bytes 编码内容 * @return 编码结果 */ public static String crc16(int[] bytes) { int res = INITIAL_VALUE; for (int data : bytes) { res = res ^ data; for (int i = 0; i < BITS_OF_BYTE; i++) { res = (res & 0x0001) == 1 ? (res >> 1) ^ POLYNOMIAL : res >> 1; } } return Integer.toHexString(revert(res)); } /** * 翻转16位的高八位和低八位字节 低位在前 LH * @param src 翻转数字 * @return 翻转结果 */ private static int revert(int src) { int lowByte = (src & 0xFF00) >> 8; int highByte = (src & 0x00FF) << 8; return lowByte | highByte; } public static int getCRC(byte[] bytes) { int CRC = 0x0000ffff; int POLYNOMIAL = 0x0000a001; for(byte b : bytes) { CRC = CRC ^ (b & 0x000000ff) ; for(int j = 0; j < 8; j++) { CRC = (CRC & 0x0001) == 1 ? (CRC >> 1) ^ POLYNOMIAL : CRC >> 1; } } return revert(CRC); } public static void main(String[] args) { // int[] data = new int[]{0x01, 0x03, 0x03, 0xd7, 0x00, 0x01}; // System.out.println(Crc16Utils.crc16(data)); String[] addrs= {"1810","188D","190A","1987","1A04","1A81","1AFE","1B7B","1BF8","1C75","1CF2","1D6F","1DEC","1E69","1EE6","1F63","1FE0","205D","20DA","2157","21D4","2251","22CE","234B","23C8","2445","24C2","253F","25BC","2639","26B6","2733","27B0","282D","28AA","2927","29A4","2A21","2A9E","2B1B"}; int[] cmds=null; int ad1=0,ad2=0; String s1,s2=null,crc=null; String cmdstr=null; for(String adr : addrs) { ad1=Integer.parseInt(adr.substring(0,2),16); ad2=Integer.parseInt(adr.substring(2,4),16); cmds=new int[] {0x01,0x03,ad1,ad2,0x00,0x7d}; crc=Crc16Utils.crc16(cmds); System.out.println(crc); s1=(ad1>0x7f?"(byte)0x":"0x")+adr.substring(0,2); s2=(ad2>0x7f?"(byte)0x":"0x")+adr.substring(2,4); cmdstr="0x01,0x03,"+s1+","+s2+",0x00,0x7d"; if(crc.length()>3) { ad1=Integer.parseInt(crc.substring(0,2),16); ad2=Integer.parseInt(crc.substring(2,4),16); s1=(ad1>0x7f?"(byte)0x":"0x")+crc.substring(0,2); s2=(ad2>0x7f?"(byte)0x":"0x")+crc.substring(2,4); cmdstr+=","+s1+","+s2; } System.out.println(cmdstr); } // System.out.println(Integer.toHexString(Crc16Utils.getCRC(data2))); } }