Compare byte values?

前端 未结 2 658
情话喂你
情话喂你 2021-01-07 18:03

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

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

...retur

相关标签:
2条回答
  • 2021-01-07 18:41

    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.

    0 讨论(0)
  • 2021-01-07 18:44
    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);
    
    0 讨论(0)
提交回复
热议问题