Check if bytes are 0x00

What is the most readable (and idiomatic) for writing this method?

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

I need a function that checks the first three bytes of a file that does not start with 00 00 00.

Many byte manipulations were not performed. The above code seems wrong to me because the ttype is being deduced Int32.

+5
source share
3 answers

t defined as type Int32

Yup, because the operator |(like most operators) is not defined for byte- bytes are increased to values int. (For details, see Section 7.11.1 of the C # 4 Specification.)

But, considering that you want to compare only with 0, anyway.

Personally, I will simply 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);

.

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

:

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

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

Linq:

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;
}
+2

All Articles