Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bit level operations in Java

Tags:

java

bit

I'm trying to make some bit operations in Java for applying masks, represent sets etc. Why:

int one=1;
int two=2;
int andop=1&2;
System.out.println(andop);

Prints a "0" when is supposed to be "3":

0...001
0...010
_______
0...011

And how can I get that behavior?

Thanks in advance

like image 647
Addev Avatar asked Oct 21 '11 07:10

Addev


2 Answers

Use the binary 'or' operator:

int andop = 1 | 2;

The binary 'and' operator will leave bits sets that are in both sides; in the case of 1 and 2 that is no bits at all.

like image 86
trojanfoe Avatar answered Nov 07 '22 19:11

trojanfoe


You mixed up bitwise OR and bitwise AND

like image 37
Konstantin Pribluda Avatar answered Nov 07 '22 21:11

Konstantin Pribluda