Since I have recently used java to connect some smart devices of the Internet of Things, after experiencing various toss in this composition, some methods and experiences summarized, I hope to help students on the road. Below is a method to calculate the checksum
public class CheckNum { /* *//** * Algorithm for finding checksum * @param b Byte array that requires checksum * @return checksum *//* 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){ //Over 255, use complement (Complement code = original code inverted + 1) sum = ~sum; sum = sum + 1; } String temp = Integer.toHexString( (byte) (sum & 0xff) & 0xFF); return temp; }*/ /* ** * Calculate checksum * @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();
// If the length of the check digit is not enough, add 0, here is a two-digit check
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 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);//The correct result should be 8d
}*/
}
A calculation checksum method for connecting IoT devices with java, I hope it will be useful to everyone.
Originally engaged in the Internet of Things industry for more than two years, I hope to exchange and learn from my peers.