James James - 1 month ago 17
Java Question

Checking to see if I understand basic Java bitwise operations

An example code in a class reading had the following code:

// adjustSpacing will set bits in the spacing word to indicate the
// type of spacing adjustment to be done, LEADING OR TRAILING.

public void adjustSpacing(int spacingValue)
{
spacing |= spacingValue;
}


I have never used the bitwise operators before as I never needed them. I looked up how to do the operations and they seem pretty straightforward but I would like to check that I actually have it.

Take

A = 1010 1000

B = 0111 0111

A |= B -> 1111 1111

A &= B -> 0010 0000

From what I can tell, the |= result will have all of the ones from both A & B;
the &= result will have only the ones present in both.

Did I get that right? Reminds me of doing 2's complement, almost.

As to why I listed compiler design, this class is advanced programming languages and that method comes from a java based lexical analyzer for the C language. We are covering compilation and interpretation right now.

Answer

The bitwise & operator performs a bitwise AND operation.

The bitwise ^ operator performs a bitwise exclusive OR operation.

The bitwise | operator performs a bitwise inclusive OR operation.

From what I can tell, the |= result will have all of the ones from both A & B;

Yes. If either of A or B has a 1 for a particular bit, or, if both have 1, then the resulting bit is 1.

the &= result will have only the ones present in both.

Again, YES. Only if both A and B has 1 in their bit, then the resulting bit would be 1; else 0.