Search code examples
javabitmask

How and Where to use Bit Mask in java


Please explain to me how and where to use Bit Mask in java:

I don't understand the code below:

int bitmask=1;    
if ((bitmask & 1) == 1) // what it does

The other questions dint exactly answer why?


Solution

  • The result value for the operator & is the bitwise AND of the operand values.

    It means that when applied to two integers (in binary representation), it will result in an integer where each bit will be set to 1 only if both bits at the same position where 1, else to 0.

    int a =     0b01010111;
    int b =     0b11111111;
    //result in 0b01010111
    
    System.out.println(a & b);//print 87 which is decimal representation of 0101 0111
    

    Now if you understood my explanation, the example you show us is the equivalent of

    if(true)//because 1 == 1 will always be true.
    

    As doing an & on two same numbers (1 and 1) will automatically return this number (in that case 1).