Compare byte values?

38,663

Solution 1

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);

Solution 2

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.

Share:
38,663

Related videos on Youtube

Hans En
Author by

Hans En

Updated on August 31, 2020

Comments

  • Hans En
    Hans En almost 4 years

    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;
    
    • hansvb
      hansvb over 11 years
      Are you getting any compiler warnings? I think those might be integer literals (and then the comparison might be done as int, with your negative number in the array and the positive integer literal).