Java如何处理位运算结果及判断运算结果的正负?
Great question! Let's unpack this clearly—understanding how Java handles signed integers and bitwise operations is key to solving your confusion.
核心前提:Java整数全以补码存储
First off, every int in Java is a 32-bit signed integer stored in two's complement format. This isn't just for operations—it's how all integers exist in memory, whether you're doing arithmetic, bitwise work, or just storing a value.
拆解你的示例
Let's walk through your code step by step (I'll truncate leading identical bits for readability, but remember all values are 32 bits total):
int x = -5:- 5's binary is
000...000101 - To get -5's two's complement: flip all bits (one's complement:
111...111010) then add 1 →111...111011
- 5's binary is
int y = 8: Binary is000...0001000
x & y → 8
When we do a bitwise AND (&), each corresponding bit is compared:
111...111011 & 000...0001000 = 000...0001000
The result's highest bit (sign bit) is 0, so Java interprets it as a positive integer—8, which matches your output.
x | y → -5 (not 11)
Bitwise OR (|) combines bits where either is 1:
111...111011 | 000...0001000 = 111...111011
This result is exactly the two's complement of -5! Java doesn't "recognize" it as -5 out of thin air—it follows the rules for signed integers:
- Check the highest bit: it's 1, so this is a negative number.
- Convert the two's complement back to decimal: flip all bits (
000...000100) then add 1 →000...000101(which is 5), then prepend the negative sign → -5.
If you wanted to treat this as an unsigned integer, you could use Integer.toUnsignedString(x|y) to get 4294967291 (2³² -5), but Java defaults to signed interpretation for int.
所有位运算都基于补码吗?
Absolutely. Every bitwise operation in Java (&, |, ^, <<, >>, >>>) operates directly on the two's complement binary of the integers. The result of the operation is also a two's complement value, which Java then interprets as a signed integer (unless you explicitly use unsigned parsing methods).
关于汇编指令IAND/IOR
Those assembly instructions align perfectly with this logic. IAND and IOR perform bitwise AND/OR directly on the binary values stored in registers—which are the two's complement representations of your Java ints. There's no extra conversion happening here; the low-level operations mirror the high-level Java behavior because they're both working with the same binary data.
内容的提问来源于stack exchange,提问作者aravind

