Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 627
BuddyJoe Avatar asked Feb 28 '13 19:02

BuddyJoe


People also ask

Can bytes be in decimal?

A byte is a group of 8 bits. A bit is the most basic unit and can be either 1 or 0. A byte is not just 8 values between 0 and 1, but 256 (28) different combinations (rather permutations) ranging from 00000000 via e.g. 01010101 to 11111111 . Thus, one byte can represent a decimal number between 0(00) and 255.

What is 0x00 in Java?

The 0x00 notation is just an alternative way to write integer constants, and if the integer constant is in the range -128 to 127, then it can be used as a byte.

How bytes are represented?

How many bits in a byte? A bit is represented by a lowercase b. While a byte can hold a letter or symbol, a bit is the smallest unit of storage, storing just one binary digit. The standard number of bits in a byte is eight, but that number can vary from system to system, depending on the hardware.

How do you check if an array is all zero in Java?

To check if an array has no elements, get length property of the array and check if the length is zero. In the following example, we will initialize an integer array with empty array. And then use equal to comparison operator in an If Else statement to check if array length is zero.


1 Answers

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.

like image 175
Jon Skeet Avatar answered Oct 05 '22 23:10

Jon Skeet