0

How do I know a Longitudinal redundancy check is correctly calculated and how is it used to ensure that data before is not corrupt?

This is how I'm calculating it right now in Java but how do I know I am calculating it correctly given the data?

byte[] testMessage1 = {0x02, // STX
        0x10,0x2,0xA,0x10,0x10,0x7,0x8, // Data 02, A, 10, 7, 8
        0x03, // ETX
        0x2^0xA^0x10^0x7^0x8^0x03}; // LRC calculated from the data (with the DLE removed) plus the ETX 


public static byte calculateLRC2(byte[] bytes) {
    byte checksum = 0;
    for (int i = 1; i < bytes.length - 1; i++) {
        checksum ^= (bytes[i] & 0xFF);          
    }
    return checksum;
}
Johnathan Au
  • 5,244
  • 18
  • 70
  • 128
  • Are you sending this data to another system that can decode it? The calculation is very simple (XOR), so I don't think you would have a problem. Not sure what the application is. – OldProgrammer Jan 31 '14 at 22:55
  • Sorry, I didn't mention this in my post. I am not sending a the data. The example "testMessage" data is the data I am using to parse. I basically have to find ETX, STX and see if the message is valid. – Johnathan Au Jan 31 '14 at 23:07
  • Then the LRC in the test message should match the value you calculate from the data bytes. – OldProgrammer Jan 31 '14 at 23:10
  • Does this therefore mean I have to eliminate the 0x10's which are acting as delimiters when I am calculating them? – Johnathan Au Jan 31 '14 at 23:12
  • 1
    I don't know if that is part of the "data" or not. Depends on your protocol's interpretation. Try it and see. – OldProgrammer Jan 31 '14 at 23:21

1 Answers1

0

You are looking for answer of a wrong question in my opinion because LRC check is to find out weather you are reading the data correctly or not not the other way around. But if you just want to validate your implementation create unit tests from real examples. Please remember that LRC is to validate if the data read from the source was correct (and not tempered or faulty) so LRC must be available within the data your code is just to make sure that LRC you are calculating and LRC available in the source are matching. If in any case you don't have access to sample data then you can try online tools e.g. asecuritysite.com. Coming back to code following code is working for me in java for validation of credit card magnetic strip read. see it running online here.

String str = ";4564456445644564=1012101123456789?";
byte lrc = 0x00;
byte [] binaryValue = str.getBytes();

for(byte b : binaryValue) {

    lrc ^= b;
}

// lrc msut be between 48 to 95
lrc %= 48; 
lrc += 48;

System.out.println("LRC: " + (char) lrc);
Mubashar
  • 12,300
  • 11
  • 66
  • 95