Longitudinal redundancy check
In telecommunication, a longitudinal redundancy check (LRC) or horizontal redundancy check is a form of redundancy check that is applied independently to each of a parallel group of bit streams. The data must be divided into transmission blocks, to which the additional check data is added.
The term usually applies to a single parity bit per bit stream, although it could also be used to refer to a larger Hamming code. While simple longitudinal parity can only detect errors, it can be combined with additional error control coding, such as a transverse redundancy check, to correct errors.
Telecom standard ISO 1155 states that a longitudinal redundancy check for a sequence of bytes may be computed in software by the following algorithm:
Set LRC = 0
For each byte b in the buffer
do
Set LRC = (LRC + b) AND 0xFF
end do
Set LRC = (((LRC XOR 0xFF) + 1) AND 0xFF)
which can be expressed as "the 8-bit two's-complement value of the sum of all bytes modulo 28."
An 8-bit LRC such as this is equivalent to a cyclic redundancy check using the polynomial x8+1, but the independence of the bit streams is less clear when looked at that way.
Many protocols use such an XOR-based longitudinal redundancy check byte (often called Block Check Character or BCC), including the IEC 62056-21 standard for electrical meter reading, smart cards as defined in ISO 7816, and the ACCESS.bus protocol.
[edit] C#
/// <summary>
/// Longitudinal Redundancy Check (LRC) calculator for a byte array. Warning: This code has no warranty. Check it, and fix it before using.
/// </summary>
public static byte calculateLRC(byte[] bytes)
{
/* https://gist.github.com/953550
* http://en.wikipedia.org/wiki/Longitudinal_redundancy_check
*/
byte LRC = (byte)0;
for (int i = 0; i < bytes.Length; i++)
{
LRC += bytes[i]; // (x & 0xFF) is implicit when storing to a byte.
}
LRC = ((LRC ^ 0xFF) + 1); // (x & 0xFF) is implicit when storing to a byte.
return LRC;
}
[edit] Java
/**
* Calculates the checksum in compliance with the ISO 1155 standard
* More info: http://en.wikipedia.org/wiki/Longitudinal_redundancy_check
* @param data array to calculate checksum for
* @return returns the calculated checksum in byte format
*/
public byte calculateLRC(byte[] data) {
byte checksum = 0;
for (int i = 0; i <= data.length - 1; i++) {
checksum = (byte) ((checksum + data[i]) & 0xFF);
}
checksum = (byte) (((checksum ^ 0xFF) + 1) & 0xFF);
return checksum;
}
[edit] References
This article incorporates public domain material from the General Services Administration document "Federal Standard 1037C" (in support of MIL-STD-188).