需求
对一个十六进制的字符串进行BCC校验
方法
private static String XORCheck(String rawMsg) {// 16进制字符串需要转成10进制数组进行校验,然后再返回16进制字符串用于与原来的字符匹配byte[] bytes = HexDumpMsgFormat.hexStr2DesBytes(rawMsg);return BytesUtil.bytesXORCheck(bytes);}
/*** 十六进制字符串转10进制字节数组*/public static byte[] hexStr2DesBytes(String hex) {int len = (hex.length() / 2);byte[] result = new byte[len];int k = 0;for (int i = 0; i < len; i++) {byte high = (byte) (Character.digit(hex.charAt(k), 16) & 0xff);byte low = (byte) (Character.digit(hex.charAt(k + 1), 16) & 0xff);result[i] = (byte) (high << 4 | low);k += 2;}return result;}
如果是普通的字符串
bytesXORCheck("xxxxx".getBytes())
/*** OXR校验* 在线BBC校验: http://www.ip33.com/bcc.html** @param bytes* @return*/public static String bytesXORCheck(byte[] bytes) {int nAll = 0;for (int nTemp : bytes) {nAll = nAll ^ nTemp;}return String.format("%02X", nAll & 0xff);}
验证
BCC校验(异或校验)在线计算_ip33.com
BCC一般是对前端内容校验,然后拼到最后,给设备下发指令。