J'ai ce tableau d'octets:
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; }
3 Réponses :
Utilisez le code suivant à la place:
// 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; }
Je travaillais sur Modbus à l'aide de Java 1.6, essayé le code ci-dessus et cela ne fonctionnait que partiellement? Convenu sur certains CRC, mal sur les autres. Je l'ai étudié un peu plus et j'ai vu que j'ai eu un problème avec une extension de signe. Je me suis masqué sur les hauts bits (voir correctement ci-dessous) et maintenant cela fonctionne bien. Remarque: tous les calculs CRC ne sont pas identiques, Modbus est un peu différent:
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
serait CRC32 ou doit-il être CRC16? Si 32 va bien, avez-vous essayé d'utiliser le La sortie est la suivante: P > CRC32 code> dans
java.util.zip code>?
F9DB8E67