Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How and Where to use Bit Mask in java [duplicate]

Tags:

java

bitmask

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
like image 898
Spartan Avatar asked Apr 12 '15 03:04

Spartan


1 Answers

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

like image 76
Jean-François Savard Avatar answered Nov 06 '22 14:11

Jean-François Savard