2012-09-11 44 views
5

我在計算java-byte數組的CRC-16實現時遇到了問題。基本上我正在嘗試將字節發送到開始寫入標籤的RFID。通過在mac上查看tcpdump命令,我可以看到數組的校驗和值。但我的目標是自己生成它。這是我應該生成0xbe,0xd9的字節數組:crc16實現java

byte[] bytes = new byte[]{(byte) 0x55,(byte) 0x08,(byte) 0x68, (byte) 0x14, 
          (byte) 0x93, (byte) 0x01, (byte) 0x00, (byte) 0x00, 
          (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x06, 
          (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x00, 
          (byte) 0x13, (byte) 0x50, (byte) 0x00, (byte) 0x00, 
          (byte) 0x00, (byte) 0x22, (byte) 0x09, (byte) 0x11}; 

0x55是標頭。正如文件所說,它將被排除在外。

每當我在java上嘗試這個數組(0xbe,0xd9)時,RFID就起作用。我的問題是生成這些校驗和值。我搜索了幾乎整個網頁,但沒有機會。我找不到任何生成0xbe,0xd9的算法。

任何想法是最受歡迎的。提前致謝。

編輯:here is the protocol是提供RFID

回答

2

真的知道這是在C的Java的正確翻譯crc16算法.... 但它顯示您的示例正確的結果!

請在使用之前將其他結果與Mac的CRC16進行比較,並對其進行壓力測試

public class Crc16 { 
public static void main(String... a) { 
    byte[] bytes = new byte[] { (byte) 0x08, (byte) 0x68, (byte) 0x14, (byte) 0x93, (byte) 0x01, (byte) 0x00, 
      (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x06, (byte) 0x00, (byte) 0x00, (byte) 0x01, 
      (byte) 0x00, (byte) 0x13, (byte) 0x50, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x22, (byte) 0x09, 
      (byte) 0x11 }; 
    byte[] byteStr = new byte[4]; 
    Integer crcRes = new Crc16().calculate_crc(bytes); 
    System.out.println(Integer.toHexString(crcRes)); 

    byteStr[0] = (byte) ((crcRes & 0x000000ff)); 
    byteStr[1] = (byte) ((crcRes & 0x0000ff00) >>> 8); 

    System.out.printf("%02X\n%02X", byteStr[0],byteStr[1]); 
} 

int calculate_crc(byte[] bytes) { 
    int i; 
    int crc_value = 0; 
    for (int len = 0; len < bytes.length; len++) { 
     for (i = 0x80; i != 0; i >>= 1) { 
      if ((crc_value & 0x8000) != 0) { 
       crc_value = (crc_value << 1)^0x8005; 
      } else { 
       crc_value = crc_value << 1; 
      } 
      if ((bytes[len] & i) != 0) { 
       crc_value ^= 0x8005; 
      } 
     } 
    } 
    return crc_value; 
} 

} 
+0

我不知道該如何謝謝你。非常appriciated。但我不能不問,你認爲這兩者之間的問題是什麼? –

0

也許你在找這個?

Crc16 in java

我用同樣的陣列(變量「表」),在這個方法:

public Integer computeCrc16(byte[] data) { 
    int crc = 0x0000; 
    for (byte b : data) { 
     crc = (crc >>> 8)^table[((crc^b) & 0xff)]; 

    } 

    return (int) crc; 
} 
+0

非常感謝您的回覆。我已經嘗試過,但沒有機會。它不給我0xbe 0xd9字節。 –

+0

我正在閱讀文檔。我將嘗試在Java附錄A中實現算法(你是否已經嘗試過這樣做?) –

+0

實際上,我沒有太多有關c的信息。基本上我沒有把它轉換成java。但我認爲它和你的文章是一樣的實現。我只複製了附錄a的查找表字節,並用它來試用。並再次沒有成功。我正在進行一個項目。實現它,那是我的最後一步。 –

0

Java運行時(rt.jar)中已有CRC16實現。

請參閱源碼的grepcode

你可能會看到它在你的IDE如果搜索CRC16:

picture of class search for CRC16