Hans En
Hans En

Reputation: 926

Compare byte values?

I'm curious to know why, when I compare a byte array with a value...

boolean match = ((data[0] & 0xFF) == 0xFE);

...returns true, while...

boolean match = (data[0] == 0xFE);

...does not? data is a byte array with

data[0] = (byte) 0xFE;

Upvotes: 23

Views: 43699

Answers (2)

Snicolas
Snicolas

Reputation: 38168

boolean match = ((data[0] & 0xFF) == 0xFE);

compares integers as 0xFF is an integer, this expression will scale up your byte data[0] to an int and compare what's inside the parenthesis to a second int 0xFE(254). As you say data[0] is (byte)0xFE, it will first be scaled to the integer 0xFE and compared to the integer 0xFE, so this works.

boolean match = (data[0] == 0xFE);

compares a byte to the int 0xFE : 254

data[0] = (byte) 0xFE; 

is a byte (so it's signed) and its value is -2.

-2 is not equal to 254, so that's why you must compare data[0] as a byte or as scale it up to an integer before comparing it the integer 0xFE.

A simpler comparison could be

boolean match = (data[0] == (byte)0xFE);

Upvotes: 27

Michael Dillon
Michael Dillon

Reputation: 32392

I believe that it has to do with promoting 0xFF to an int with sign extension. In the first expression, 0xFE is also promoted to an int and therefore the result of data[0] & 0xFF is also an int and an int comparison is done.

But in the second code sample, there is no operation being done and so there is no promotion to int. That is to say, that data[0] does not get promoted to int but 0xFE is an int.

Upvotes: 3

Related Questions