具体代码如下:
public String checkSum(String command) {
byte[] bytes = new byte[1];
byte sum = 0;
byte[] content = hexString2Bytes(command);
for (byte b : content) {
sum += b;
}
bytes[0] = sum;
return command + bytes2HexString(bytes);
}
public static byte[] hexString2Bytes(String hex) {
int length = hex.length() / 2;
byte[] bytes = new byte[length];
for (int i = 0; i < length; i++) {
String sub = hex.substring(2 * i, 2 * i + 2);
bytes[i] = (byte) (Integer.valueOf(sub, 16) & 0xff);
}
return bytes;
}
public static String bytes2HexString(byte[] bytes) {
StringBuilder builder = new StringBuilder();
for (byte aByte : bytes) {
builder.append(String.format("%02x", aByte).toUpperCase());
}
return builder.toString();
}