如何计算纵向冗余校验(LRC)? [英] How can I calculate Longitudinal Redundancy Check (LRC)?

查看:202
本文介绍了如何计算纵向冗余校验(LRC)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了维基百科中的示例: http://en.wikipedia.org/wiki/Longitudinal_redundancy_check

I've tried the example from wikipedia: http://en.wikipedia.org/wiki/Longitudinal_redundancy_check

这是lrc(C#)的代码:

This is the code for lrc (C#):

/// <summary>
/// Longitudinal Redundancy Check (LRC) calculator for a byte array. 
/// ex) DATA (hex 6 bytes): 02 30 30 31 23 03
///     LRC  (hex 1 byte ): EC    
/// </summary> 
public static byte calculateLRC(byte[] bytes)
{
    byte LRC = 0x00;
    for (int i = 0; i < bytes.Length; i++)
    {
        LRC = (LRC + bytes[i]) & 0xFF; 
    }
    return ((LRC ^ 0xFF) + 1) & 0xFF;
}   

它说结果是"EC",但我得到"71",我做错了什么?

It said the result is "EC" but I get "71", what I'm doing wrong?

谢谢.

推荐答案

这是一个清理的版本,它不会执行所有这些无用的操作(而不是每次都丢弃高位,而是一次丢弃所有高位).结束),它给出了您观察到的结果.这是使用加法的版本,但末尾有一个否定符号-最好减去并跳过该否定符号.即使发生溢出,这也是有效的转换.

Here's a cleaned up version that doesn't do all those useless operations (instead of discarding the high bits every time, they're discarded all at once in the end), and it gives the result you observed. This is the version that uses addition, but that has a negation at the end - might as well subtract and skip the negation. That's a valid transformation even in the case of overflow.

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

这是替代的LRC(字节的简单xor)

Here's the alternative LRC (a simple xor of bytes)

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

在这种情况下,无论是在代码(未编译)还是在预期结果方面,维基百科都是错误的.

And Wikipedia is simply wrong in this case, both in the code (doesn't compile) and in the expected result.

这篇关于如何计算纵向冗余校验(LRC)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆