Bit Level Operations in Java

I am trying to perform some bits of operation in Java for applying masks, representing sets, etc. Why:

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

Prints "0" if it is assumed that "3":

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

And how can I get this behavior?

Thanks in advance

+6
source share
5 answers

Use the binary 'or' operator:

 int andop = 1 | 2; 

The binary operator "and" will leave sets of bits that are on both sides; in case 1 and 2 , which are not bits at all.

+10
source

You mixed bitwise AND and bitwise AND

+10
source

You are looking for the bitwise "OR" and not the "AND":

 int both = one | two; 

"OR" says: "bit n must be 1 if it is 1 in input x * or * it is 1 in input y"

"And" says: "bit n must be 1 if it is 1 at input x * and * it is 1 at input y"

+5
source

& should be like 1

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

answer = 0
| is or, one 1 is ok

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

answer = 3

+2
source

The best solution is to use enumerations with int ONE (1), TWO (2) values, etc. and EnumSet .

From JavaDoc:

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

0
source

Source: https://habr.com/ru/post/899769/


All Articles