0

how to calculate longitudinal redundancy check (LRC) for Modbus ASCII in java?

I want to calculate LRC for Modbus ascii protocol using java. I have searched for the solutions online but haven't found any.

I used this online lrc calculator to calculate lrc http://www.metools.info/encoding/ecod127.html

I just found this one solution on StackOverflow here is that How can I calculate Longitudinal Redundancy Check (LRC)?

 byte[] byte = {31, 30, 31, 30, 31, 31}

  public static byte calculateLRC(byte[] bytes)

{
  int LRC = 0;
  for (int i = 0; i < bytes.Length; i++)
  {
      LRC -= bytes[i];
  }
  return (byte)LRC;
}

As expected the LRC I should get is "DC" but I'm getting 72 as output.

Does anyone know how to calculate LRC for modbus ascii protocol. Thanks in advance :)

1 Answers1

0

72 is the correct Modbus ASCII LRC for {31, 30, 31, 30, 31, 31}. It goes into the messages as the two characters "48" (72 in hex). See https://www.simplymodbus.ca/ASCII.htm .

If instead I compute the LRC of {49, 48, 49, 48, 49, 49}, I get 220, or the 0xDC you are expecting.

Your problem is that you think you put hexadecimal in your Java code, but it is being interpreted as decimal. What you probably meant was:

byte[] byte = {0x31, 0x30, 0x31, 0x30, 0x31, 0x31};

Then you will get 220.

Mark Adler
  • 101,978
  • 13
  • 118
  • 158