2013-07-04 21 views
7

我有這樣的字節數組:獲取一個字節數組的CRC校驗並將其添加到該字節數組

static byte[] buf = new byte[] { (byte) 0x01, (byte) 0x04, (byte)0x00, (byte)0x01,(byte)0x00, (byte) 0x01}; 

現在,此字節數組的CRC校驗應該是0x60的,的0x0A。我希望Java代碼重新創建這個校驗和,但是我似乎無法重新創建它。我試過crc16:

static int crc16(final byte[] buffer) { 
    int crc = 0xFFFF; 

    for (int j = 0; j < buffer.length ; j++) { 
     crc = ((crc >>> 8) | (crc << 8))& 0xffff; 
     crc ^= (buffer[j] & 0xff);//byte to int, trunc sign 
     crc ^= ((crc & 0xff) >> 4); 
     crc ^= (crc << 12) & 0xffff; 
     crc ^= ((crc & 0xFF) << 5) & 0xffff; 
    } 
    crc &= 0xffff; 
    return crc; 

} 

並使用Integer.toHexString()轉換它們,但沒有結果匹配正確的CRC。請問有人可以根據CRC公式指出正確的方向。

回答

10

使用下面的代碼來代替:

// Compute the MODBUS RTU CRC 
private static int ModRTU_CRC(byte[] buf, int len) 
{ 
    int crc = 0xFFFF; 

    for (int pos = 0; pos < len; pos++) { 
    crc ^= (int)buf[pos] & 0xFF; // XOR byte into least sig. byte of crc 

    for (int i = 8; i != 0; i--) { // Loop over each bit 
     if ((crc & 0x0001) != 0) {  // If the LSB is set 
     crc >>= 1;     // Shift right and XOR 0xA001 
     crc ^= 0xA001; 
     } 
     else       // Else LSB is not set 
     crc >>= 1;     // Just shift right 
    } 
    } 
// Note, this number has low and high bytes swapped, so use it accordingly (or swap bytes) 
return crc; 
} 

你可能要扭轉你的迴歸CRC以獲得正確的字節順序,但。我甚至在這裏測試過它:

http://ideone.com/PrBXVh

使用Windows計算器或東西,你可以看到,第一個結果(從上面的函數調用)給出的預期值(雖然相反)。

+0

是的,它的工作,現在我所要做的就是扭轉它。謝謝! – GreenGodot

2

我正在使用Java 1.6的modbus工作,試過上面的代碼,它只是部分工作?同意一些社區康復中心,其他人不對。我對它進行了更多的研究,並發現我在擴展簽名方面遇到了問題。我掩蓋了高位(見下面的FIX),現在效果很好。 注:所有CRC Calcs(計算)是不一樣的,Modbus是有點不同:

public static int getCRC(byte[] buf, int len) { 
    int crc = 0xFFFF; 
    int val = 0; 

     for (int pos = 0; pos < len; pos++) { 
     crc ^= (int)(0x00ff & buf[pos]); // FIX HERE -- XOR byte into least sig. byte of crc 

     for (int i = 8; i != 0; i--) { // Loop over each bit 
      if ((crc & 0x0001) != 0) {  // If the LSB is set 
      crc >>= 1;     // Shift right and XOR 0xA001 
      crc ^= 0xA001; 
      } 
      else       // Else LSB is not set 
      crc >>= 1;     // Just shift right 
     } 
     } 
    // Note, crc has low and high bytes swapped, so use it accordingly (or swap bytes) 
    val = (crc & 0xff) << 8; 
    val = val + ((crc >> 8) & 0xff); 
    System.out.printf("Calculated a CRC of 0x%x, swapped: 0x%x\n", crc, val); 
    return val; 

} // end GetCRC 
2

會CRC32做,或是否必須CRC16?如果32是好的,你有沒有試過在java.util.zip中使用CRC32

import java.util.zip.CRC32; 

byte[] buf = new byte[] { (byte) 0x01, (byte) 0x04, (byte)0x00, (byte)0x01,(byte)0x00, (byte) 0x01}; 
CRC32 crc32 = new CRC32(); 
crc32.update(buf); 
System.out.printf("%X\n", crc32.getValue()); 

輸出是:

F9DB8E67 

然後,你可以做你想做最重要的是什麼額外的計算。

相關問題