C# Calculate LRC (Longitudinal Redundancy Check)

馋奶兔 提交于 2019-12-24 02:07:44

问题


I've been researching this everywhere and all the LRC implementation seems to not giving me the right answer. After spending few days on it, I decided to put my code here to see if anyone else can spot the problem.

Here's the code (C#)

        //Input Data = "31303030315E315E31303030325E315E31303030375E39395E31303032325E36353631335E"
        //LRC Answer = "30"
        private static string LRC(string Data)
        {
            int checksum = 0;
            foreach (char c in GetStringFromHex(Data))
            {
                checksum ^= Convert.ToByte(c);
            }


            string hex = checksum.ToString("X2");

            Console.WriteLine("Calculated LRC = " + hex);

            return hex;
        }





    //Supporting Function used in LRC function
    private static string GetStringFromHex(string s)
    {
        string result = "";
        string s2 = s.Replace(" ", "");
        for (int i = 0; i < s2.Length; i += 2)
        {
            result += Convert.ToChar(int.Parse(s2.Substring(i, 2), System.Globalization.NumberStyles.HexNumber));
        }
        return result;
    }

The current output shows "Calculated LRC = 33". However, the right answer is "30". Can anyone spot what's wrong with this?

Any help will be fantastic!


回答1:


After several testing, it is confirmed LRC should include ETX and exclude STX during the LRC calculation.



来源:https://stackoverflow.com/questions/29057120/c-sharp-calculate-lrc-longitudinal-redundancy-check

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!