我需要计算一些需要通过蓝牙发送的字符串的校验和。我需要发送 5 个字符串,因此,我需要创建一个函数来计算校验和。
我需要帮助创建函数来执行此操作。
这些是字符串:
/**String to calculate the Checksum*/
String message_part1 = send_command+" "+num_byte_trama1+" "+num_byte_variable+" "+pos_reg_1+" "+sendValue1;
String message_part2 = send_command+" "+num_byte_trama1+" "+num_byte_variable+" "+pos_reg_2+" "+sendValue2;
String message_part3 = send_command+" "+num_byte_trama1+" "+num_byte_variable+" "+pos_reg_3+" "+sendValue3;
String message_part4 = send_command+" "+num_byte_trama2+" "+num_byte_variable+" "+pos_reg_save_request;
String message_part5 = send_command+" "+num_byte_trama2+" "+num_byte_variable+" "+pos_reg_save_status;
/**Full message*/
String message_full1 = start_thread+" "+message_part1+" "+Checksum;
String message_full2 = start_thread+" "+message_part2+" "+Checksum;
String message_full3 = start_thread+" "+message_part3+" "+Checksum;
String message_full4 = start_thread+" "+message_part4+" "+Checksum;
String message_full5 = start_thread+" "+message_part5+" "+Checksum;
所以,我需要创建一个函数来读取一个字符串,获取这个字符串的字节,计算校验和,然后将这个值转换为十六进制。
这就是我所做的。我不知道它是否正确,我还没有完成 int 到 hex 的转换:
private String CalcChecksum (String message) {
byte[] byte_calc = message.getBytes();
int checksum = 0;
for (int byte_index = 0; byte_index < byte_calc.length; byte_index++) {
checksum += byte_calc[byte_index];
}
return checksum;
}