Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare byte values?

Tags:

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; 
like image 525
Hans En Avatar asked Nov 15 '12 06:11

Hans En


People also ask

Can we compare bytes?

We can use compareTo(Byte anotherByte) to compare two Byte objects numerically. The following table lists the return value from compareTo(Byte anotherByte) . if this Byte is numerically greater than the argument Byte (signed comparison).

How to compare byte[] Java?

equals(byte[] a, byte[] a2) method returns true if the two specified arrays of bytes are equal to one another. Two arrays are equal if they contain the same elements in the same order. Two array references are considered equal if both are null.

What are the byte values?

byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters.


2 Answers

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); 
like image 101
Snicolas Avatar answered Oct 03 '22 17:10

Snicolas


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.

like image 23
Michael Dillon Avatar answered Oct 03 '22 19:10

Michael Dillon