Getting the CRC checksum of a byte array and adding it to that byte array

后端 未结 3 1895
庸人自扰
庸人自扰 2020-12-31 11:50

I have this byte array:

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

Now, th

3条回答
  •  没有蜡笔的小新
    2020-12-31 12:30

    I was working on modbus using Java 1.6, tried the above code and it only partially worked? Agreed on some CRCs, wrong on others. I researched it a bit more, and saw I had a problem with sign extension. I masked off the high bits (see FIX HERE below) and now it works great. NOTE: All CRC calcs are not the same, MODBUS is a bit different:

        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
    

提交回复
热议问题