BuddyJoe
BuddyJoe

Reputation: 71101

Checking if Bytes are 0x00

What is the most readable (and idiomatic) to write this method?

private bool BytesAreValid(byte[] bytes) {
    var t = (bytes[0] | bytes[1] | bytes[2]);
    return t != 0;
}

I need a function which tests the first three bytes of a file that it's not begin with 00 00 00.

Haven't done much byte manipulation. The code above doesn't seem correct to me, since t is inferred of type Int32.

Upvotes: 5

Views: 8335

Answers (3)

Ken Kin
Ken Kin

Reputation: 4683

private bool BytesAreValid(byte[] bytes) {
    return !bytes.Take(3).SequenceEqual(new byte[] { 0, 0, 0 });
}

Upvotes: 3

Tim
Tim

Reputation: 887

To anticipate variable array lengths and avoid null reference exceptions:

private bool BytesAreValid(byte[] bytes)
{
    if (bytes == null) return false;

    return !Array.Exists(bytes, x => x == 0);
}

Non-Linq version:

private bool BytesAreValid(byte[] bytes)
{
    if (bytes == null) return false;

    for (int i = 0; i < bytes.Length; i++)
    {
        if (bytes[i] == 0) return false;
    }
    return true;
}

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1499860

t is type-inferred to be an Int32

Yup, because the | operator (like most operators) isn't defined for byte - the bytes are promoted to int values. (See section 7.11.1 of the C# 4 spec for details.)

But given that you only want to compare it with 0, that's fine anyway.

Personally I'd just write it as:

return bytes[0] != 0 && bytes[1] != 0 && bytes[2] != 0;

Or even:

return (bytes[0] != 0) && (bytes[1] != 0) && (bytes[2] != 0);

Both of these seem clearer to me.

Upvotes: 14

Related Questions