lysergic-acid
lysergic-acid

Reputation: 20050

Can the result of a bitwise AND operator be negative (in Java)

I have the following piece of code:

int SOME_MASK = 0x0000ffff;

int value = /* some value */;
int something = SOME_MASK & value;

// WHY IS "something" guaranteed to be non-negative ?
if (something != NEGATIVE_CONSTANT) {
    // do something here....
}

I keep getting the FindBugs analysis warning:

Correctness - Bad comparison of nonnegative value with negative constant This code compares a value that is guaranteed to be non-negative with a negative constant.

The warning pops up for the line where comparing the bitwise AND result with the negative constant.

I am not sure why a Bitwise AND result is guaranteed to be non-negative? is this always the case?

Upvotes: 0

Views: 2827

Answers (5)

Stephen C
Stephen C

Reputation: 719561

Can the result of a bitwise AND operator be negative (in Java)

In general - Yes.

In the case of your example - No.

In Java, integers are represented in two's complement signed binary representation. One characteristic of this representation is that the most significant (i.e. left-most) bit is one for a negative number and zero for a positive number.

In your example, you are ANDing with 0x0000ffff, and that is setting the top 16 bits to zero. That means that the result of that expression cannot be a negative number.


By contrast, if you ANDed with 0xffff0000, the result could be negative.

Upvotes: 2

kennytm
kennytm

Reputation: 523724

The result of bitwise-AND can be negative, e.g. (-1) & (-1) is definitely -1.

However, if either operand is nonnegative, the result must also be nonnegative. This is because in 2's complement representation, a negative number must have its 31st bit set, and a nonnegative number must have its 31st bit cleared. Since & will set a bit only if both operand's bit is set, the result is negative if and only if both inputs are negative.

Since SOME_MASK = 0xffff is positive, the result of SOME_MASK & value will never be negative.

Upvotes: 3

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79875

The bitwise AND of two negative integers is always negative. The bitwise AND of two integers, where one or both are positive, is always positive. To see why, think about the binary representation, and what happens to the highest bit.

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075537

something is guaranteed not to be negative because Java's signed int type uses the most significant bit for sign, and that bit is cleared (0) in SOME_MASK. Since something is the result of something being ANDed with that mask, it can't have that bit set, so it can't be negative.

Upvotes: 2

Evgeny
Evgeny

Reputation: 2161

When SOME_MASK starts with a '0' bit, the result of SOME_MASK & value must be positive.

Upvotes: 3

Related Questions