Addev
Addev

Reputation: 32233

Bit level operations in Java

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

Upvotes: 6

Views: 990

Answers (5)

MariuszS
MariuszS

Reputation: 31567

Better solution is to use enums with int values ONE(1), TWO(2) etc, and EnumSet.

From JavaDoc:

Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based "bit flags."

Upvotes: 0

刘伟科
刘伟科

Reputation: 432

& must be both 1

0...001
&...&&&
0...010
_______
0...000

answer = 0
| is or ,one 1 is OK

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

answer = 3

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500525

You're looking for a bitwise "OR", not "AND":

int both = one | two;

"OR" says: "bit n should be 1 if it's 1 in input x *or* it's 1 in input y"

"AND" says: "bit n should be 1 if it's 1 in input x *and* it's 1 in input y"

Upvotes: 5

Konstantin Pribluda
Konstantin Pribluda

Reputation: 12367

You mixed up bitwise OR and bitwise AND

Upvotes: 10

trojanfoe
trojanfoe

Reputation: 122391

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.

Upvotes: 11

Related Questions