2
   private byte CalculateChecksum(byte[] realbytesend)
        {
            int checksum = 0;
            for (int i = 0; i < realbytesend.Length ; i++)
            {
                string strchecksum = realbytesend.GetValue(i).ToString();
                int intchecksum = Convert.ToInt32(strchecksum);
                checksum += intchecksum;
            }
            string csumbit = checksum.ToString("X"); //Gives you hexadecimal
            string checksumbit = string.Format("0x{0}", csumbit);

            style = NumberStyles.HexNumber;

            bytechecksum = Byte.Parse(checksumbit, style);
            return bytechecksum;
        }

when i debug this code, there is an error message with ' System.FormatException:"The input string is malformed." ' i dont know why it happen.

i already tried convert.ToByte and byte.parse(string), but i dont know why it doesnt work!!

i want you to help me...

1
  • That is a very complicated way of calculating a checksum. But, your checksum variable is an integer, and very likely greater than 0xff (the max value for a byte). What do you expect Byte.Parse(checksumbit, style) to do with a number that size? What is the point of all the conversions to and from a string? Why not calculate a sum (or do some XOR operations) and then mask the result with 0xff Commented Feb 8, 2019 at 5:38

1 Answer 1

4

There is a lot of problems with your code. However, the main problem is you are playing Conversion-Football from string to int to byte. Don't do that.. Instead, keep it simple.

Your method can be boiled down to the following

private byte CalculateChecksum(byte[] realbytesend)
{
   byte checksum = 0;
   unchecked // allow overflows
   {
      for (var i = 0; i < realbytesend.Length; i++)
         checksum += realbytesend[i];
   }
   return checksum;
}

or foreach

...

unchecked // allow overflows
{
   foreach (var b in realbytesend)
      checksum += b;
}

...

or Linq

private byte CalculateChecksum(byte[] realbytesend)
  => realbytesend.Aggregate((sum, i) => unchecked((byte)(sum + i)));

unchecked (C# Reference)

The unchecked keyword is used to suppress overflow-checking for integral-type arithmetic operations and conversions.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.