/* package whatever; // don't place package name! */
/* The class name doesn't have to be Main, as long as the class is not public. */
class Main
{
private 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;
}
// 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]; // 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;
}
{
byte[] buf = new byte[] { (byte) 0x01, (byte) 0x04, (byte)0x00, (byte)0x01,(byte)0x00, (byte) 0x01};
int crc = ModRTU_CRC(buf, 6);
//java.io.BufferedReader r = new java.io.BufferedReader (new java.io.InputStreamReader (System.in));
crc = crc16(buf);
//while (!(s=r.readLine()).startsWith("42")) System.out.print(crc);
}
}
LyogcGFja2FnZSB3aGF0ZXZlcjsgLy8gZG9uJ3QgcGxhY2UgcGFja2FnZSBuYW1lISAqLwoKLyogVGhlIGNsYXNzIG5hbWUgZG9lc24ndCBoYXZlIHRvIGJlIE1haW4sIGFzIGxvbmcgYXMgdGhlIGNsYXNzIGlzIG5vdCBwdWJsaWMuICovCmNsYXNzIE1haW4KewogIHByaXZhdGUgc3RhdGljIGludCBjcmMxNihmaW5hbCBieXRlW10gYnVmZmVyKSB7CiAgICBpbnQgY3JjID0gMHhGRkZGOwoKICAgIGZvciAoaW50IGogPSAwOyBqIDwgYnVmZmVyLmxlbmd0aCA7IGorKykgewogICAgICAgIGNyYyA9ICgoY3JjICA+Pj4gOCkgfCAoY3JjICA8PCA4KSApJiAweGZmZmY7CiAgICAgICAgY3JjIF49IChidWZmZXJbal0gJiAweGZmKTsvL2J5dGUgdG8gaW50LCB0cnVuYyBzaWduCiAgICAgICAgY3JjIF49ICgoY3JjICYgMHhmZikgPj4gNCk7CiAgICAgICAgY3JjIF49IChjcmMgPDwgMTIpICYgMHhmZmZmOwogICAgICAgIGNyYyBePSAoKGNyYyAmIDB4RkYpIDw8IDUpICYgMHhmZmZmOwogICAgfQogICAgY3JjICY9IDB4ZmZmZjsKICAgIHJldHVybiBjcmM7CgogIH0KICAvLyBDb21wdXRlIHRoZSBNT0RCVVMgUlRVIENSQwogIHByaXZhdGUgc3RhdGljIGludCBNb2RSVFVfQ1JDKGJ5dGVbXSBidWYsIGludCBsZW4pCiAgewogICAgaW50IGNyYyA9IDB4RkZGRjsKIAogICAgZm9yIChpbnQgcG9zID0gMDsgcG9zIDwgbGVuOyBwb3MrKykgewogICAgICBjcmMgXj0gKGludClidWZbcG9zXTsgICAgICAgICAgLy8gWE9SIGJ5dGUgaW50byBsZWFzdCBzaWcuIGJ5dGUgb2YgY3JjCiAKICAgICAgZm9yIChpbnQgaSA9IDg7IGkgIT0gMDsgaS0tKSB7ICAgIC8vIExvb3Agb3ZlciBlYWNoIGJpdAogICAgICAgIGlmICgoY3JjICYgMHgwMDAxKSAhPSAwKSB7ICAgICAgLy8gSWYgdGhlIExTQiBpcyBzZXQKICAgICAgICAgIGNyYyA+Pj0gMTsgICAgICAgICAgICAgICAgICAgIC8vIFNoaWZ0IHJpZ2h0IGFuZCBYT1IgMHhBMDAxCiAgICAgICAgICBjcmMgXj0gMHhBMDAxOwogICAgICAgIH0KICAgICAgICBlbHNlICAgICAgICAgICAgICAgICAgICAgICAgICAgIC8vIEVsc2UgTFNCIGlzIG5vdCBzZXQKICAgICAgICAgIGNyYyA+Pj0gMTsgICAgICAgICAgICAgICAgICAgIC8vIEp1c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