public class StringByteCRCUtil { /** * 将十六进制的字符串转换成字节数组 * 先将十六进制字符串转为十进制再转byte * @param hexString * @return */ public static byte[] hexStrToBinaryStr(String hexString) { hexString = hexString.replaceAll(" ", ""); if ((hexString.length() % 2) != 0) { throw new IllegalArgumentException("长度不是偶数"); } int len = hexString.length(); int index = 0; byte[] bytes = new byte[len / 2]; while (index < len) { String sub = hexString.substring(index, index + 2); bytes[index/2] = (byte)Integer.parseInt(sub,16); index += 2; } return bytes; } /** * 将字节数组转换成十六进制的字符串 * * @param bs * @return */ public String toHex(byte[] bs){ StringBuilder sb=new StringBuilder(); if(bs==null||bs.length<=0){ return null; } for(int i=0;i<bs.length;i++){ int v=bs[i]&0xff; String hv= Integer.toHexString(v); if(hv.length()<2){ sb.append(0); } sb.append(hv); } return sb.toString(); } /** * Modbus协议CRC(循环冗余校验)计算(低位在前,高位在后) * @param bytes * @return */ public static String getCRC2(byte[] bytes) { int CRC = 0x0000ffff; int POLYNOMIAL = 0x0000a001; int i, j; for (i = 0; i < bytes.length; i++) { CRC ^= (int) bytes[i]; for (j = 0; j < 8; j++) { if ((CRC & 0x00000001) == 1) { CRC >>= 1; CRC ^= POLYNOMIAL; } else { CRC >>= 1; } } } // 交换高低位,低位在前高位在后 CRC = ((CRC & 0x0000FF00) >> 8) | ((CRC & 0x000000FF) << 8); String result = Integer.toHexString(CRC); return result.substring(0, 2) + " " + result.substring(2, 4); } }
关于tcp调试工具 java转译,CRC(循环冗余校验)计算,指令转发,十六进制转换byte
最新推荐文章于 2024-04-23 09:52:50 发布