fork(26) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. /* The class name doesn't have to be Main, as long as the class is not public. */
  4. class Main
  5. {
  6. private static int crc16(final byte[] buffer) {
  7. int crc = 0xFFFF;
  8.  
  9. for (int j = 0; j < buffer.length ; j++) {
  10. crc = ((crc >>> 8) | (crc << 8) )& 0xffff;
  11. crc ^= (buffer[j] & 0xff);//byte to int, trunc sign
  12. crc ^= ((crc & 0xff) >> 4);
  13. crc ^= (crc << 12) & 0xffff;
  14. crc ^= ((crc & 0xFF) << 5) & 0xffff;
  15. }
  16. crc &= 0xffff;
  17. return crc;
  18.  
  19. }
  20. // Compute the MODBUS RTU CRC
  21. private static int ModRTU_CRC(byte[] buf, int len)
  22. {
  23. int crc = 0xFFFF;
  24.  
  25. for (int pos = 0; pos < len; pos++) {
  26. crc ^= (int)buf[pos]; // XOR byte into least sig. byte of crc
  27.  
  28. for (int i = 8; i != 0; i--) { // Loop over each bit
  29. if ((crc & 0x0001) != 0) { // If the LSB is set
  30. crc >>= 1; // Shift right and XOR 0xA001
  31. crc ^= 0xA001;
  32. }
  33. else // Else LSB is not set
  34. crc >>= 1; // Just shift right
  35. }
  36. }
  37. // Note, this number has low and high bytes swapped, so use it accordingly (or swap bytes)
  38. return crc;
  39. }
  40. public static void main (String[] args) throws java.lang.Exception
  41. {
  42. byte[] buf = new byte[] { (byte) 0x01, (byte) 0x04, (byte)0x00, (byte)0x01,(byte)0x00, (byte) 0x01};
  43. int crc = ModRTU_CRC(buf, 6);
  44. //java.io.BufferedReader r = new java.io.BufferedReader (new java.io.InputStreamReader (System.in));
  45. System.out.println(crc);
  46. crc = crc16(buf);
  47. System.out.println(crc);
  48.  
  49. //while (!(s=r.readLine()).startsWith("42")) System.out.print(crc);
  50. }
  51. }
  52.  
  53.  
Success #stdin #stdout 0.07s 381248KB
stdin
1
2
10
42
11
stdout
2656
58791