TtT23
TtT23

Reputation: 7030

How to add multiple bytes and get a byte array?

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?

Upvotes: 0

Views: 1802

Answers (3)

CodesInChaos
CodesInChaos

Reputation: 108790

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

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

Upvotes: 1

Jodrell
Jodrell

Reputation: 35716

erm,

byte checksum;
foreach (var b in someBytes)
{
    checksum = (byte)((checksum + b) & 0xff);
}

Upvotes: 2

Sebastian Negraszus
Sebastian Negraszus

Reputation: 12205

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.

Upvotes: 2

Related Questions