2014-10-04 77 views
1

我試圖通過計算數組中所有數據字節總和的最低有效字節的二進制補碼來創建校驗和。校驗和計算 - 最低有效字節的二進制補碼

所以給出一個數組:

byte[] bytes = new byte[] { 0x01, 0x02 }; 

會是這樣的工作...

public static void main(String []args) 
{ 
    byte[] bytes = new byte[] { 0x01, 0x02 }; 

    BigInteger bi = new BigInteger(bytes); 

    BigInteger biRes = bi.not().add(BigInteger.ONE); 

    byte[] result = biRes.toByteArray(); 

    System.out.println("a: " + result); 

    System.out.println("b: " + javax.xml.bind.DatatypeConverter.printHexBinary(result)); 
} 

主要生產...

一個:[B @ 34bdb859 B:FEFE

這是正確的嗎?

+0

@ w0051977「不重要」的部分你不瞭解嗎? – EJP 2014-10-04 10:37:45

+0

@EJP,我刪除了我的評論,因爲它是不正確的。謝謝。 +1的問題。 – w0051977 2014-10-04 11:06:39

回答

0

只需將所有字節相加,取消結果,將其轉換或截斷爲一個字節即可完成。

+0

你爲什麼要加上字節?我認爲你的第二步和第三步很好,但我不明白第一步。 – w0051977 2014-10-04 11:07:38

0

我有另一種解決方案:

private static byte calculateChecksum8(byte[] bytes){ 

    byte result = 0; 
    for(int i = 0; i < bytes.length; i++){ 
     result += bytes[i]; 
    }  
    result = (byte) (~ result & 0xFF); 
    result = (byte) (result +1 & 0xFF); 

    String str = String.format("%02x", result); 
    System.out.println(result+" = "+str.toUpperCase()); 

    return result; 
} 

有人確認?