简体   繁体   中英

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?

SOME_MASK以0开头时, SOME_MASK & value的结果必须为正。

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.

The result of bitwise-AND can be negative, eg (-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.

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 (ie 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM