Search code examples
javabitwise-operatorsbitwise-and

bitwise AND in java with operator "&"


I just read this code following:

byte[] bts = {8, 0, 0, 0};
if ((bts[i] & 0x01) == 0x01)

Does this do the same thing as

if (bts[i] == 0x01)

If not,what's the difference between them?

And what is the first way trying to do here?


Solution

  • No, it doesn't.

    if(bts[i] == 0x01)
    

    means if bts[i] is equal to 1.

    if((bts[i] & 0x01) == 0x01) 
    

    means if the least significant bit of bts[i] is equal to 1.

    Example.

    bts[i] = 9 //1001 in binary
    
    if(bts[i] == 0x01) //false
    
    if((bts[i] & 0x01) == 0x01) //true