How and Where to use Bit Mask in java

Thanga picture Thanga · Apr 12, 2015 · Viewed 26.7k times · Source

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

Answer

Jean-François Savard picture Jean-François Savard · Apr 12, 2015

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