Witam,
Czy ktoś mógłby mi pomóc i wskazać błąd. Poniżej przedstawi=
am dwie
alternatywne metody liczące CRC 16 dla modbus: getCRC i getCRC_2.
Ogólnie wartości CRC przez nie zwracana są OK, np: dla 0103044C005641
dostaje 1333, dla 0103075C0002 dostaje 056D i są to wartości
prawidłowe.
Ale przykładowo dla 0103043E947AC0 dostaje w getCRC 2BF7, w getCRC_2
94B7 i nie są to wartości prawidłowe bo powinienem dostać: 9507.
public static byte[] getCRC(byte[] values) {
int crc =3D 0x0ffff;
byte lastbit;
for (int i =3D 0; i < values.length; i++) {
byte thisbyte =3D values[i];
crc =3D crc ^ thisbyte;
for (int shift =3D 1; shift <=3D 8; shift++) {
lastbit =3D (byte)(crc & 0x0001);
crc =3D (crc >>1) & 0x07fff;
if (lastbit =3D=3D 1) {
crc =3D crc ^ 0x0A001;
}
}
}
byte[] CRC =3D new byte[2];
CRC[0] =3D (byte) (crc & 0xff);
CRC[1] =3D (byte) ((crc >>8) & 0xff);
return CRC;
}
public static byte[] getCRC_2(byte[] values) {
int crc;
crc =3D 0x0FFFF;
for (int i =3D 0; i < values.length; i++) {
crc =3D crc ^ values[i];
for (int n =3D 0; n < 8; n++) {
if ((crc & 0x01) !=3D 0)
crc =3D (crc >>1) ^ 0x0A001;
else
crc =3D crc >>1;
}
}
byte[] CRC =3D new byte[2];
CRC[0] =3D (byte) (crc & 0x0ff);
CRC[1] =3D (byte) ((crc >>8) & 0x0ff);
return CRC;
}
Co jest nie tak? Z góry wielkie dzięki za pomoc.
Pozdrawiam
Kamil