1

I'm trying to calculate an LRC (Longitudinal Redundancy Check) value with Python. My Python code is pulled from other posts on StackOverflow. It looks like this:

lrc = 0
for b in message:
    lrc ^= b
print lrc

If I plug in the value '\x02\x47\x30\x30\x03', I get an LRC value of 70 or 0x46 (F) However, I am expecting a value of 68 - 0x44 (D) instead.

I have calculated the correct LRC value via C# code:

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

If I plug in the same byte array values, I get the expected result of 0x44.

Functionally, the code looks very similar. So I'm wondering what the difference is between the code. Is it my input value? Should I format my string differently?

metalcharms
  • 56
  • 1
  • 7

2 Answers2

2

Arrays are 0-ordered in C#, so by starting iteration from int i = 1; you are skipping 1st byte.

Python result is correct one.

Fixed reference code:

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

To avoid such mistake you should consider using foreach syntactic sugar (although I'm not familiar with C# practices).

/edit

To skip first byte in Python simply use slice syntax:

lrc = 0
for b in message[1:]:
    lrc ^= b
print lrc
Community
  • 1
  • 1
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
  • Appreciate the input but the C# result is the one I am looking for. The Python implementation is the one that I am unhappy with. Good point with noting that it starts at 1 though. I will explore that further – metalcharms Apr 10 '15 at 20:29
-1

So I figured out the answer to my question. Thanks to Nsh for his insight. I found a way to make the algorithm work. I just had to skip the first byte in the for-loop. There's probably a better way to do this but it was quick and it's readable.

def calcLRC(input):
    input=input.decode('hex')
    lrc = 0
    i = 0
    message = bytearray(input)
    for b in message:
        if(i == 0):
            pass
        else:
            lrc ^= b
        i+=1;
    return lrc

It now returns the expected 0x44 in my use case.

metalcharms
  • 56
  • 1
  • 7