|
由于最近在用java对接一些物联网的智能设备,在这构成中经历了各种折腾之后,总结出来的一些方法和经验,希望能帮助在路上的同学们。下边是一个计算校验和的方法
- public class CheckNum {
-
- /* *//**
- * 求校验和的算法
- * @param b 需要求校验和的字节数组
- * @return 校验和
- *//*
- public static String sumCheck(byte[] b, int len){
- int sum = 0;
- for(int i = 0; i < len; i++){
- sum = sum + b[i];
- }
- if(sum > 0xff){ //超过了255,使用补码(补码 = 原码取反 + 1)
- sum = ~sum;
- sum = sum + 1;
- }
- String temp = Integer.toHexString( (byte) (sum & 0xff) & 0xFF);
- return temp;
- }*/
- /**
- * 计算校验和
- * @param data
- * @return
- */
- public static String makeChecksum(String data) {
- if (data == null || data.equals("")) {
- return "";
- }
- int total = 0;
- int len = data.length();
- int num = 0;
- while (num < len) {
- String s = data.substring(num, num + 2);
- // System.out.println(s);
- total += Integer.parseInt(s, 16);
- num = num + 2;
- }
- /**
- * 用256求余最大是255,即16进制的FF
- */
- int mod = total % 256;
- String hex = Integer.toHexString(mod);
- len = hex.length();
- // 如果不够校验位的长度,补0,这里用的是两位校验
- if (len < 2) {
- hex = "0" + hex;
- }
- return hex;
- }
- public static void main(String[] args) {
- String hex = makeChecksum(" 00 00 01 59 2C 22 0D 19 08 14 39 03 00 00 00 00 00 00 00 00 00 00 00 00 03".replace(" ", ""));
- System.out.println(hex);
- }
- /* @Test
- public void test1(){
- byte[] b = new byte[7];
- b[0] = (byte) 0xfd;
- b[1] = (byte) 0xfc;
- b[2] = (byte) 0x08;
- b[3] = (byte) 0x80;
- b[4] = (byte) 0x02;
- b[5] = (byte) 0x00;
- b[6] = (byte) 0x0a;
- String temp = sumCheck(b, 7);
- System.out.printf(temp);//正确的结果应该是8d
- }*/
- }
复制代码
|
|