0

Given a byte array

byte[] someBytes = { 0xFF, 0xFE, 0xFE, 0xFF, 0x11, 0x00 ,0x00 ,0x00 ,0x00}

What's the best to add up all the bytes? Manually adding all of the bytes by hand as hex numbers would yield 40B on my above example so preferably I'd like to end up with something like:

byte[] byteSum = { 0x04, 0x0B }

Actually, all I really need is the 0x0B part (Used for checksum). Checksum is calculated by 0x0B XOR 0x55 (Which yields 0x5E) in this case.

I understand this isn't a normal addition of bytes, but this is how the checksum is calculated.

Manually looping through the byte array and adding them results in an integer sum.

What's the most concise way of doing this?

4
  • You will want to use the modulo operator: 0x040B % 0x0100 == 0x000B The modulo operator divides one number with the other and returns the rest of the division. Commented Jul 11, 2013 at 8:38
  • @Nolonar That oughta be pretty useful once I figure out how to get 0x040B :D Thanks Commented Jul 11, 2013 at 8:39
  • I don't understand how adding is supposed to yield 0x40B. The sum is 1129 or 0x469. What's your definition of "add"? Commented Jul 11, 2013 at 8:46
  • @SebastianNegraszus oh sorry, 5E is actually the checksum of first 9 bytes being added then XORing by 0x55. I'll add that to the detail. Commented Jul 11, 2013 at 8:48

3 Answers 3

2

erm,

byte checksum;
foreach (var b in someBytes)
{
    checksum = (byte)((checksum + b) & 0xff);
}
Sign up to request clarification or add additional context in comments.

1 Comment

the casts to ushort are unnecessary since + automatically promotes to int.
2

I'm not sure if I understand your question... But this is how I would do it:

byte sum = 0;
foreach (byte b in someBytes)
{
    unchecked
    {
        sum += b;
    }
}

But this does not yield 0x0B, but 0x69.

2 Comments

He obviously wants to ADD the byte, and when it overflows, create a NEW byte, hence the byte array.
unchecked avoids the casting and masking, +1, lucky that byte has no sign.
1

Using LINQ's sum and casting to byte in the end:

unchecked
{
    var checksum = (byte)(someBytes.Sum(b => (long)b) ^ 0x55);
}

1 Comment

@Jodrell Given the maximal size of an array is 2 billion bytes in the current CLR, this is plain impossible. It's also larger than the maximal RAM size of the current AMD64 CPUs. Avoiding overflows in the reason I chose long over int.

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.