How can I calculate Longitudinal Redundancy Check (LRC)?

前端 未结 6 878
盖世英雄少女心
盖世英雄少女心 2021-01-19 07:35

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

This is the code for lrc (C#):

///          


        
6条回答
  •  太阳男子
    2021-01-19 08:19

    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;
    }
    

    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.

提交回复
热议问题