2013-08-05 330 views
-1

我需要計算一些需要通過藍牙發送的字符串的校驗和。有5個字符串需要發送,所以我需要創建一個函數來計算校驗和。計算校驗和android

我需要幫助創建功能來做到這一點。

這些字符串:

/**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; 

所以,我需要創建一個函數讀取一個字符串,獲取這個字符串的字節數,計算校驗和,然後該值轉換爲十六進制。

這就是我所做的。我不知道這是否是correcto,我還沒有做過的int進制轉換:

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; 
} 
+0

發表我已經做了 – masmic

回答

0

我用.hashCode(String)方法簡單地創建一個SMS體+日期的散列碼,以避免解析短信過程中的重複。 這將返回一個32位(帶符號)整數。對我來說,這提供了足夠的熵來接受它作爲消息的唯一性,這是相當快的計算和平臺獨立。